使用Python APS按顺序运行挂起的任务



假设我有两个cron触发器:

trigger1 = CronTrigger(second='0,20,40')
trigger2 = CronTrigger(second='0,10,20,30,40,50') 

我创建了这样的调度器:

scheduler = BlockingScheduler()
scheduler.add_job(lambda: method1(param1, param2), trigger=trigger1)
scheduler.add_job(lambda: method2(param1, param3), trigger=trigger2)

这两种方法确实有效:

def method1(s, t):
print("doing work in method1")
time.sleep(2)
print("doing work in method1")
time.sleep(2)
print("doing work in method1")
time.sleep(2)
def method2(s, t):
print("doing work in method2")
time.sleep(2)
print("doing work in method2")
time.sleep(2)
print("doing work in method2")
time.sleep(2)

当计划的时间重叠(例如0、20、30(,并且调度器在该时间安排了两个作业时,它似乎并行地运行它们。输出如下:

doing work in method1
doing work in method2
doing work in method1
doing work in method2
doing work in method1
doing work in method2

问题是:如何设置它,以便按顺序运行挂起的作业。即,如果两个作业的时间重叠,则运行第一个作业直到完成,然后运行第二个作业。

编辑:我之所以使用apsschedule库,是因为我需要类似cron的功能。我需要这个过程在一天中的特定时间间隔运行。

使用DebugExecutor。例如:

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.executors.debug import DebugExecutor
def foo1():
print("x")
def foo2():
time.sleep(3)
print("y")
scheduler = BlockingScheduler()
scheduler.add_executor(DebugExecutor(), "consecutive")
scheduler.add_job(foo1, 'interval', max_instances=1, seconds=1, executor="consecutive")
scheduler.add_job(foo2, 'interval', max_instances=1, seconds=5, executor="consecutive")

使用DebugExecutor是个好主意,此外,我需要在.add_job()中为misire_grace_time参数指定一个高值,以避免在多个作业具有相同执行间隔时跳过运行

最新更新