from apscheduler.schedulers.background import BackgroundScheduler, BlockingScheduler from apscheduler.jobstores.redis import RedisJobStore from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor def print_args(*args): """ 要定時執行的函數 :param args: 參數 :return: None """ for arg in args: print(arg) # 執行器 常用的就線程池和進程池兩種 thread_pool = ThreadPoolExecutor(30) process_pool = ProcessPoolExecutor(5) executors = { 'thread': thread_pool, 'process': process_pool } # 存儲器 默認使用內存,對定時任務丟失什么的不敏感,對定時任務執行要求低 redis_store = RedisJobStore(host='172.16.120.120', port='6379') sqlite_store = SQLAlchemyJobStore(url='sqlite:///jobs.sqlite') jobstores = { 'redis': redis_store, 'default': sqlite_store } # 刪除被持久化的定時任務 redis_store.remove_all_jobs() # 調度器 # 調度器配置 job_defaults = { 'coalesce': False, 'max_instances': 5, 'misfire_grace_time': 60 } # coalesce:當由於某種原因導致某個job積攢了好幾次沒有實際運行(比如說系統掛了5分鍾后恢復,有一個任務是每分鍾跑一次的,按道理說這5分鍾內本來是“計划”運行5次的,但實際沒有執行),如果coalesce為True,下次這個job被submit給executor時,只會執行1次,也就是最后這次,如果為False,那么會執行5次(不一定,因為還有其他條件,看后面misfire_grace_time的解釋) # max_instance: 就是說同一個job同一時間最多有幾個實例再跑,比如一個耗時10分鍾的job,被指定每分鍾運行1次,如果我們max_instance值為5,那么在第6~10分鍾上,新的運行實例不會被執行,因為已經有5個實例在跑了 # misfire_grace_time:設想和上述coalesce類似的場景,如果一個job本來14:00有一次執行,但是由於某種原因沒有被調度上,現在14:01了,這個14:00的運行實例被提交時,會檢查它預訂運行的時間和當下時間的差值(這里是1分鍾),大於我們設置的30秒限制,那么這個運行實例不會被執行。 # scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, daemonic=False) # 實例化定時任務調度對象(阻塞方式) scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, daemonic=False) # 實例化定時任務調度對象(非阻塞方式) scheduler.add_job(id='my_job_id1', jobstore='redis',executor='processpool',func=print_args, args=["Hello,World!"], trigger='date', run_date='2018-06-18 12:56:00') # 表示在2018-06-18 12:56:00執行 # 觸發器 # 三種執行方式 trigger='date' trigger='interval' trigger='cron' # 1.date 定時調度 默認 指定時間執行一次 scheduler.add_job(func=print_args, args=["Hello,World!"], trigger='date', run_date='2018-06-18 12:56:00') # 表示在2018-06-18 12:56:00執行 # 2.interval 間隔調度 指定時間間隔重復執行 scheduler.add_job(func=print_args, args=['a', 'b', 'c'], trigger='interval', days=3, hours=17, minutes=19,seconds=7) # 表示每隔3天17時19分07秒執行一次任務 scheduler.add_job(func=print_args, args=['a', 'b', 'c'], trigger='interval', hours=17, minutes=19,seconds=7) # 表示每隔17時19分07秒執行一次任務 scheduler.add_job(func=print_args, args=['a', 'b', 'c'], trigger='interval', minutes=19, seconds=7) # 表示每隔19分07秒執行一次任務 scheduler.add_job(func=print_args, args=['a', 'b', 'c'], trigger='interval', minutes=19) # 表示每隔19分執行一次任務 scheduler.add_job(func=print_args, args=['a', 'b', 'c'], trigger='interval', seconds=1) # 表示每秒執行一次任務 scheduler.add_job(func=print_args, args=['a', 'b', 'c'], trigger='interval', seconds=0.5) # 表示每500毫秒執行一次任務 # 3. cron 定時調度(指定時刻執行) # [參數取值范圍] # year (int|str) – 4-digit year -(表示四位數的年份,如2008年) # month (int|str) – month (1-12) -(表示取值范圍為1-12月) # day (int|str) – day of the (1-31) -(表示取值范圍為1-31日) # week (int|str) – ISO week (1-53) -(格里歷2006年12月31日可以寫成2006年-W52-7(擴展形式)或2006W527(緊湊形式)) # day_of_week (int|str) – number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun) - (表示一周中的第幾天,既可以用0-6表示也可以用其英語縮寫表示) # hour (int|str) – hour (0-23) - (表示取值范圍為0-23時) # minute (int|str) – minute (0-59) - (表示取值范圍為0-59分) # second (int|str) – second (0-59) - (表示取值范圍為0-59秒) # start_date (datetime|str) – earliest possible date/time to trigger on (inclusive) - (表示開始時間) # end_date (datetime|str) – latest possible date/time to trigger on (inclusive) - (表示結束時間) # timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations (defaults to scheduler timezone) -(表示時區取值) # [參數取值格式] # * any Fire on every value 如: day='*' 即,每天執行 # */a any Fire every a values, starting from the minimum 如: hour='*/2' 即,每兩小時執行 # a-b any Fire on any value within the a-b range (a must be smaller than b) 如: minute='6-8,21-23' 即,6-8點和21-23點執行 # a-b/c any Fire every c values within the a-b range 如: minute='9-21/2' 即,9點-21點之間每兩小時執行 # xth y day Fire on the x -th occurrence of weekday y within the month # last x day Fire on the last occurrence of weekday x within the month # last day Fire on the last day within the month # x,y,z any Fire on any matching expression; can combine any number of any of the above expressions # 表達式之間用逗號進行分隔 scheduler.add_job(func=print_args, args=['a', 'b', 'c'], trigger='cron', year=2018, month=3, day=21, hour=21, minute=19, second=8) # 表示2018年3月21日21時19分08秒執行 scheduler.add_job(func=print_args, args=['a', 'b', 'c'], trigger='cron', day_of_week='mon-fri', hour=5, minute=30,start_date='2016-06-06',end_date='2018-08-08') # 表示周一到周五的5點半執行,有效日期是2016-06-06 00:00:00 至 2018-08-08 00:00:00 scheduler.add_job(func=print_args, args=['a', 'b', 'c'], trigger='cron', second='*/10') # 表示每10秒執行該程序一次,相當於interval 間隔調度中seconds = 10 scheduler.start() # 開始調度 scheduler.shutdown() # 停止調度 scheduler.pause_job(job_id='my_job_id') # 暫停指定JOB調度 scheduler.resume_job(job_id='my_job_id') # 恢復指定JOB調度 scheduler.pause() # 暫停調度 scheduler.resume() # 恢復調度
參考資料