python定时器库-apscheduler-BackgroundScheduler

基本用法
  • 主函数

    # coding=utf-8
    # @Time    : 2020/10/30 14:03
    # @Author  : Leo
    # @Email   : [email protected]
    # @File    : demo.py
    
    
    from apscheduler.schedulers.background import BackgroundScheduler
    from datetime import  datetime
    from trigger_manage import TriggerManager
    import time
    
    
    def tick(**kwargs):
        print('Hi  %s Tick! The time is: %s' % (kwargs['name'], datetime.now()))
    
    if __name__ == '__main__':
        scheduler = BackgroundScheduler()
        # 触发器设置每隔多少时间执行一次  {"timeInterval": 5, "timeUnit": 's'}表示每隔5秒触发一次
        trigger = TriggerManager.interval_trigger(conf={"timeInterval": 5, "timeUnit": 's'})
    
        # 添加任务:指定执行的函数、触发器、函数的参数、任务的id(唯一标识,方便根据id修改、删除任务)
        scheduler.add_job(tick, trigger,
                          kwargs={
                              "name": "leo"
                          },
                          id="1")
        scheduler.add_job(tick, trigger,
                          kwargs={
                              "name": "bob"
                          },
                          id="2")
        scheduler.start()
    
        #  BackgroundScheduler 运行在Backgroud,但是并不会阻止主程序自己终止,而主程序终止后,BackgroundScheduler 也会终止。
        #  所以要主线程一直执行
        try:
            # 模拟主进程持续运行
            while True:
                time.sleep(2)
                # print('sleep')
        except(KeyboardInterrupt, SystemExit):
            # Not strictly necessary if daemonic mode is enabled but should be done if possible
            scheduler.shutdown()
            print('Exit The Job!')
    
  • 触发管理器

    # coding=utf-8
    # @Time    : 2020/10/30 14:20
    # @Author  : Leo
    # @Email   : [email protected]
    # @File    : trigger_manage.py
    
    
    import pytz
    from apscheduler.triggers.interval import IntervalTrigger
    
    
    TZ = pytz.timezone("Asia/Shanghai")
    
    class TriggerManager(object):
        """
        触发管理器
        """
        def __init__(self):
            pass
    
        @classmethod
        def interval_trigger(cls, conf):
            """
            间隔触发方法
            :param conf: 配置计划时间
            :return:
            """
            time_args = {"s": 0, "m": 0, "h": 0, "d": 0, "w": 0}
    
            time_unit = conf['timeUnit']
            time_interval = conf['timeInterval']
            time_args[time_unit] = time_interval
    
            return IntervalTrigger(seconds=time_args['s'],
                                   minutes=time_args['m'],
                                   hours=time_args['h'],
                                   days=time_args['d'],
                                   weeks=time_args['w'],
                                   timezone=TZ
                                   )
    

你可能感兴趣的:(python)