| 1 |
Run in the background |
| 2 |
===================== |
| 3 |
|
| 4 |
Out of the box it is not possible to run the schedule in the background. |
| 5 |
However, you can create a thread yourself and use it to run jobs without blocking the main thread. |
| 6 |
This is an example of how you could do this: |
| 7 |
|
| 8 |
.. code-block:: python |
| 9 |
|
| 10 |
import threading |
| 11 |
import time |
| 12 |
|
| 13 |
import schedule |
| 14 |
|
| 15 |
|
| 16 |
def run_continuously(interval=1): |
| 17 |
"""Continuously run, while executing pending jobs at each |
| 18 |
elapsed time interval. |
| 19 |
@return cease_continuous_run: threading. Event which can |
| 20 |
be set to cease continuous run. Please note that it is |
| 21 |
*intended behavior that run_continuously() does not run |
| 22 |
missed jobs*. For example, if you've registered a job that |
| 23 |
should run every minute and you set a continuous run |
| 24 |
interval of one hour then your job won't be run 60 times |
| 25 |
at each interval but only once. |
| 26 |
""" |
| 27 |
cease_continuous_run = threading.Event() |
| 28 |
|
| 29 |
class ScheduleThread(threading.Thread): |
| 30 |
@classmethod |
| 31 |
def run(cls): |
| 32 |
while not cease_continuous_run.is_set(): |
| 33 |
schedule.run_pending() |
| 34 |
time.sleep(interval) |
| 35 |
|
| 36 |
continuous_thread = ScheduleThread() |
| 37 |
continuous_thread.start() |
| 38 |
return cease_continuous_run |
| 39 |
|
| 40 |
|
| 41 |
def background_job(): |
| 42 |
print('Hello from the background thread') |
| 43 |
|
| 44 |
|
| 45 |
schedule.every().second.do(background_job) |
| 46 |
|
| 47 |
# Start the background thread |
| 48 |
stop_run_continuously = run_continuously() |
| 49 |
|
| 50 |
# Do some other things... |
| 51 |
time.sleep(10) |
| 52 |
|
| 53 |
# Stop the background thread |
| 54 |
stop_run_continuously.set() |
| 55 |
|
| 56 |
|