APScheduler回调函数 - 如何在作业完成后在python中调用一些函数/模块?

时间:2017-12-26 12:47:27

标签: python python-2.7 callback apscheduler

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

我将作为Django模型的作业存储在DB中。完成后,我想在表格中将其标记为embeds_many_relations.map { |_, v| v.key }

2 个答案:

答案 0 :(得分:1)

最简单和通用的方法是将回调函数添加到计划作业的末尾。您还可以在调度程序类的基础上构建,以在任务结束时包含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)

答案 1 :(得分:0)

enter image description here允许挂接APScheduler的各种Listener。我已经使用EVENT_JOB_SUBMITTED成功获得了我的工作的下次运行时间

(已更新) 我确认是否可以挂接这些事件。

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