Python,为每个方法安排一个线程并行线程

时间:2019-02-15 23:42:32

标签: python python-3.x multithreading schedule

我如何并行运行这两个任务,但是如果带有该方法名称的线程尚未完成,请跳过此方法,直到下一次调度迭代为止?

因为现在它在运行时为同一方法创建了一个新线程。

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)

1 个答案:

答案 0 :(得分:0)

用另一个名为apscheduler的模块进行计算。 它具有参数 max_instances:1 并记录如下内容

*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()

您不需要创建 threading.Thread ,因为模块会为您执行此操作。只需传递您的方法即可。