APScheduler 回调函数 - 如何在作业完成时调用 python 中的某些 funtion/module?

APScheduler callback function - how can I call some funtion/module in python when a job is completed?

您好,我在 Django 项目中使用 APScheduler。作业完成后如何计划 python 中的函数调用?一个回调函数。

我将作业作为 Django 模型存储在数据库中。完成后,我想在 table.

中将其标记为 completed=1

最简单和通用的方法是将回调函数添加到计划作业的末尾。您还可以在调度程序 class 之上构建,以在任务结束时包含 self.function_callback()。

简单示例:

def tick():
    print('Tick! The time is: %s' % datetime.now())
    time.sleep(10)
    function_cb()

def function_cb():
    print "CallBack Function"
    #Do Something

if __name__ == '__main__':
    scheduler = AsyncIOScheduler()
    scheduler.add_job(tick, 'interval', seconds=2)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
    # Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
    try:
        asyncio.get_event_loop().run_forever()
    except (KeyboardInterrupt, SystemExit):
        pass
        scheduler.shutdown(wait=False)

Listener allows to hook various events 的 APScheduler。我已使用 EVENT_JOB_SUBMITTED.

成功获得 下一个 运行 时间 我的工作

(更新) 我确认它是否能够 hook 这些事件。

from datetime import datetime
import os
from logging import getLogger, StreamHandler, Filter, basicConfig, INFO

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR


logger = getLogger(__name__)
logger.setLevel(INFO)


def tick():
    now = datetime.now()
    logger.info('Tick! The time is: %s' % now)
    if now.second % 2 == 0:
        raise Exception('now.second % 2 == 0')


if __name__ == '__main__':
    sh = StreamHandler()
    sh.addFilter(Filter('__main__'))
    basicConfig(
            handlers = [sh],
            format='[%(asctime)s] %(name)s %(levelname)s: %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
    )

    def my_listener(event):
        if event.exception:
            logger.info('The job crashed')
        else:
            logger.info('The job worked')

    scheduler = BlockingScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass

执行这段代码时,输​​出结果如下:

Interrupt: Press ENTER or type command to continue
Press Ctrl+C to exit
[2019-11-30 09:24:12] __main__ INFO: Tick! The time is: 2019-11-30 09:24:12.663142
[2019-11-30 09:24:12] __main__ INFO: The job crashed
[2019-11-30 09:24:15] __main__ INFO: Tick! The time is: 2019-11-30 09:24:15.665845
[2019-11-30 09:24:15] __main__ INFO: The job worked
[2019-11-30 09:24:18] __main__ INFO: Tick! The time is: 2019-11-30 09:24:18.663215
[2019-11-30 09:24:18] __main__ INFO: The job crashed