dkruchok
dkruchok

Reputation: 1899

Python, schedule parallel Threads with one thread for each method

How I can run those two tasks in parallel, but if the Thread with the name of the method was not finished yet just skip this method till the next schedule iteration?

Because now it creates a new thread for the same method while it is running.

def task1:
   #do task1

def task1:
   #do task2

def run_threaded(job_fn):
  job_thread = threading.Thread(target=job_fn)
  job_thread.start()


schedule.every(5).minutes.do(run_threaded, task1)
schedule.every(3).minutes.do(run_threaded, task2)

while True:
  schedule.run_pending()
  time.sleep(1)

Upvotes: 3

Views: 3445

Answers (1)

dkruchok
dkruchok

Reputation: 1899

Figured out with another module called apscheduler. It has parameter max_instances:1 and log thing like this

*Execution of job "task1 (trigger: interval[0:50:0], next run at: 2019-02-16 11:38:23 EET)" skipped: maximum number of running instances reached (1)*

scheduler = BackgroundScheduler(executors=executors, job_defaults=job_defaults)

scheduler.add_job(task1, 'interval', minutes=5)
scheduler.add_job(task2, 'interval', minutes=7)
scheduler.start()

You don't need to create a threading.Thread because module doing this for you. Just pass your method.

Upvotes: 1

Related Questions