zoukankan      html  css  js  c++  java
  • python apscheduler的使用

    # !/usr/bin/env python3
    # -*- coding: utf-8 -*-

    import pytz
    from util import log, cfg
    from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
    from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
    from apscheduler.schedulers.blocking import BlockingScheduler
    logger = log.get_logger('timed_task', 'INFO')


    def init():
    logger.info("scheduler_handler main start run")


    def test():
    print('测试成功')


    def main():
    # 执行需要初始化数据的处理
    init()

    # 时区设定
    timezone = pytz.timezone('Asia/Shanghai')

    # 执行器
    executors = {'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(3)}
    job_defaults = {'coalesce': True, 'max_instances': 3}
    # 阻塞主线程的运行
    scheduler = BlockingScheduler(timezone=timezone, executors=executors, job_defaults=job_defaults)

    ####################################################################################################################

    if cfg.sys == 'Linux':
    scheduler.add_job(func=test, trigger='interval', seconds=10)
    scheduler.add_job(func=test, trigger="cron", day_of_week='*', hour='23', minute='50')

    else:
    scheduler.add_job(func=test, trigger='interval', seconds=10)

    ####################################################################################################################
    def event_listener(event):

    if event.exception:
    exception = str(event.exception)
    scheduled_run_time = str(event.scheduled_run_time)
    traceback = str(event.traceback)

    # 报错信息打印出来
    print(" ", "#" * 50, " ")
    logger.info(
    f"event scheduled_run_time:{scheduled_run_time} exception: {exception} traceback: {traceback}")
    print(" ", "#" * 50, " ")
    else:
    # 正常执行的处理
    pass
    #
    # # 监听正常运行和运行异常
    scheduler.add_listener(event_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)

    try:
    # 启动定时器
    scheduler.start()
    except (KeyboardInterrupt, SystemExit):
    scheduler.shutdown()
    logger.debug("scheduler start-up fail")


    if __name__ == '__main__':
    main()
  • 相关阅读:
    君の名は~ 观后感
    dp1,明天补题解
    【bzoj1222】[HNOI2001]产品加工
    Daily~Miracles
    luogu 1273有线电视网
    luogu 1373
    codeforces 721C
    codeforces 706E
    The~Best~Chanteur~宇多田ヒカル
    codeforces706D
  • 原文地址:https://www.cnblogs.com/yz-w/p/15540457.html
Copyright © 2011-2022 走看看