使用APScheduler3.0.1 實現(xiàn)定時任務的方法
需求是在某一指定的時刻執(zhí)行操作
網(wǎng)上的建議多為通過調(diào)用Scheduler的add_date_job實現(xiàn)
不過APScheduler 3.0.1與之前差異較大, 無法通過上述方法實現(xiàn)
參考 https://apscheduler.readthedocs.org/en/latest/userguide.html APScheduler 3.0.1的userguide 解決問題
from datetime import datetime
import time
import os
from apscheduler.schedulers.background import BackgroundScheduler
def tick():
print('Tick! The time is: %s' % datetime.now())
if __name__ == '__main__':
scheduler = BackgroundScheduler()
scheduler.add_job(tick, 'interval', seconds=3)
scheduler.start()
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
# This is here to simulate application activity (which keeps the main thread alive).
while True:
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown() # Not strictly necessary if daemonic mode is enabled but should be done if possible
實例的代碼實現(xiàn)每3秒執(zhí)行一次tick方法,雖然與需求不符,但發(fā)現(xiàn)add_interval_job在APScheduler 3.0.1中 已經(jīng)被
scheduler.add_job(tick, 'interval', seconds=3)
取代。
help(scheduler.add_job)得到
add_job(func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore='default', executor='default', replace_existing=False, **trigger_args) Adds the given job to the job list and wakes up the scheduler if it's already running. Any option that defaults to undefined will be replaced with the corresponding default value when the job is scheduled (which happens when the scheduler is started, or immediately if the scheduler is already running). The func argument can be given either as a callable object or a textual reference in the package.module:some.object format, where the first half (separated by :) is an importable module and the second half is a reference to the callable object, relative to the module. The trigger argument can either be: the alias name of the trigger (e.g. date, interval or cron), in which case any extra keyword arguments to this method are passed on to the trigger's constructor an instance of a trigger class
由此可知,第參數(shù)為trigger,可取值為 date、interval、cron, **trigger_args為該trigger的構(gòu)造函數(shù)。
通過源碼找到DateTrigger 的構(gòu)造函數(shù)
def __init__(self, run_date=None, timezone=None)
所以,只需將指定的時間傳入add_job
scheduler.add_job(tick, 'date', run_date='2014-11-11 14:48:00')
以上這篇使用APScheduler3.0.1 實現(xiàn)定時任務的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python?Opencv實現(xiàn)停車位識別思路詳解
這篇文章主要介紹了Opencv實現(xiàn)停車位識別,本文通過示例代碼場景分析給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07
Pycharm打印大數(shù)據(jù)文件顯示不全的解決方法
這篇文章主要介紹了Pycharm打印大數(shù)據(jù)文件顯示不全的解決方法,昨晚寫了個小爬蟲,簡單分析下發(fā)現(xiàn)可以修改請求的url,直接獲取所有目標的數(shù)據(jù),想先打印在控制臺看看,發(fā)現(xiàn)打印的數(shù)據(jù)不全,所以本文記錄了一下解決方法,需要的朋友可以參考下2024-03-03

