| 1 |
Parallel execution |
| 2 |
========================== |
| 3 |
|
| 4 |
*I am trying to execute 50 items every 10 seconds, but from the my logs it says it executes every item in 10 second schedule serially, is there a work around?* |
| 5 |
|
| 6 |
By default, schedule executes all jobs serially. The reasoning behind this is that it would be difficult to find a model for parallel execution that makes everyone happy. |
| 7 |
|
| 8 |
You can work around this limitation by running each of the jobs in its own thread: |
| 9 |
|
| 10 |
.. code-block:: python |
| 11 |
|
| 12 |
import threading |
| 13 |
import time |
| 14 |
import schedule |
| 15 |
|
| 16 |
def job(): |
| 17 |
print("I'm running on thread %s" % threading.current_thread()) |
| 18 |
|
| 19 |
def run_threaded(job_func): |
| 20 |
job_thread = threading.Thread(target=job_func) |
| 21 |
job_thread.start() |
| 22 |
|
| 23 |
schedule.every(10).seconds.do(run_threaded, job) |
| 24 |
schedule.every(10).seconds.do(run_threaded, job) |
| 25 |
schedule.every(10).seconds.do(run_threaded, job) |
| 26 |
schedule.every(10).seconds.do(run_threaded, job) |
| 27 |
schedule.every(10).seconds.do(run_threaded, job) |
| 28 |
|
| 29 |
|
| 30 |
while 1: |
| 31 |
schedule.run_pending() |
| 32 |
time.sleep(1) |
| 33 |
|
| 34 |
If you want tighter control on the number of threads use a shared jobqueue and one or more worker threads: |
| 35 |
|
| 36 |
.. code-block:: python |
| 37 |
|
| 38 |
import time |
| 39 |
import threading |
| 40 |
import schedule |
| 41 |
import queue |
| 42 |
|
| 43 |
def job(): |
| 44 |
print("I'm working") |
| 45 |
|
| 46 |
|
| 47 |
def worker_main(): |
| 48 |
while 1: |
| 49 |
job_func = jobqueue.get() |
| 50 |
job_func() |
| 51 |
jobqueue.task_done() |
| 52 |
|
| 53 |
jobqueue = queue.Queue() |
| 54 |
|
| 55 |
schedule.every(10).seconds.do(jobqueue.put, job) |
| 56 |
schedule.every(10).seconds.do(jobqueue.put, job) |
| 57 |
schedule.every(10).seconds.do(jobqueue.put, job) |
| 58 |
schedule.every(10).seconds.do(jobqueue.put, job) |
| 59 |
schedule.every(10).seconds.do(jobqueue.put, job) |
| 60 |
|
| 61 |
worker_thread = threading.Thread(target=worker_main) |
| 62 |
worker_thread.start() |
| 63 |
|
| 64 |
while 1: |
| 65 |
schedule.run_pending() |
| 66 |
time.sleep(1) |
| 67 |
|
| 68 |
This model also makes sense for a distributed application where the workers are separate processes that receive jobs from a distributed work queue. I like using beanstalkd with the beanstalkc Python library. |