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

2024-09-28 01:24:29 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个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的功能。我需要进程在一天中的特定时间之间以特定的间隔运行


Tags: intime作业sleepcronschedulerworkprint
2条回答

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

使用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")

相关问题 更多 >

    热门问题