Python - 即使在使用 'remove_job' 后 Apscheduler 也不会停止作业

Python - Apscheduler not stopping a job even after using 'remove_job'

这是我的代码

我正在使用调度程序的 remove_jobshutdown 函数来停止作业,但它继续执行。

停止作业进一步执行的正确方法是什么?

from apscheduler.schedulers.background import BlockingScheduler

def job_function():
    print "job executing"


scheduler = BlockingScheduler(standalone=True)
scheduler.add_job(job_function, 'interval', seconds=1, id='my_job_id')


scheduler.start()
scheduler.remove_job('my_job_id')
scheduler.shutdown()

因为你正在使用 BlockingScheduler ,所以首先你知道它是自然的。

所以,基本上 BlockingScheduler 是一个在前台 运行 的调度程序(即 start() 将阻止程序)。通俗地说,它 运行 在前台,所以当您调用 start() 时,调用永远不会 returns。这就是为什么从不调用 start() 之后的所有行,因此您的调度程序从未停止。

BlockingScheduler can be useful if you want to use APScheduler as a standalone scheduler (e.g. to build a daemon).


解决方案

如果您想在 运行 执行一些代码后停止您的调度程序,那么您应该选择 ApScheduler docs.

中列出的其他类型的调度程序

我推荐 BackgroundScheduler,如果你想让调度程序 运行 在你的 application/program 的后台运行,你可以 暂停 resume and remove 在任何时候,当你需要的时候。

只需要求调度程序使用 remove_function 删除 job_function 内的作业,正如@Akshay Pratap Singh 正确指出的那样,控件永远不会 returns 返回到 start()

from apscheduler.schedulers.background import BlockingScheduler

count = 0

def job_function():
    print "job executing"
    global count, scheduler

    # Execute the job till the count of 5 
    count = count + 1
    if count == 5:
        scheduler.remove_job('my_job_id')


scheduler = BlockingScheduler()
scheduler.add_job(job_function, 'interval', seconds=1, id='my_job_id')


scheduler.start()

调度程序需要从另一个线程停止。调用 scheduler.start() 的线程被调度程序阻塞。您在 scheduler.start() 之后编写的行是无法访问的代码。

我就是这样解决问题的。注意代码schedule.shutdown()所在的位置!

def do_something():
    global schedule
    print("schedule execute")
    # schedule.remove_job(id='rebate')
    schedule.shutdown(wait=False)


if __name__ == '__main__':
    global schedule
    schedule = BlockingScheduler()
    schedule.add_job(do_something, 'cron', id='rebate', month=12, day=5, hour=17, minute=47, second=35)
    schedule.start()
    print('over')