Python-Apscheduler即使在使用“remove-job”之后也不会停止作业

2024-05-14 03:29:56 发布

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

这是我的密码

我正在使用调度程序的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()

Tags: 方法函数from程序id密码my作业
3条回答

当你使用BlockingScheduler时,首先你要知道它是自然的。

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

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


解决方案

如果要在运行某些代码后停止计划程序,则应选择ApSchedulerdocs中列出的其他类型的计划程序。

我建议BackgroundScheduler,如果您希望调度程序在应用程序/程序的后台运行,您可以随时在需要时暂停、恢复和删除。

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

只要让调度器使用remove_function删除job_function中的作业,正如@Akshay Pratap Singh正确指出的,控件永远不会返回到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()

相关问题 更多 >