APScheduler 3を使用する.0.1タイミングタスクの実装

2673 ワード

需要は、指定された時点で操作を実行します.
ネット上の推奨事項は、Schedulerを呼び出すadd_であることが多い.date_job実装
でもAPScheduler 3.0.1以前との差が大きく、上記の方法では実現できない
リファレンス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
インスタンスのコードインプリメンテーションは3秒ごとにtickメソッドを実行し、需要と一致しないがadd_が発見される.interval_jobはAPScheduler 3.0にあります.1の中ですでに
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

このことから、第1パラメータはtriggerであり、値はdate、interval、cron、**trigger_とすることができるargsはtriggerの構造関数である.
ソースコードからDateTriggerのコンストラクション関数を見つける
def __init__(self, run_date=None, timezone=None)

したがって、指定された時間をadd_に転送するだけです.job
scheduler.add_job(tick, 'date', run_date='2014-11-11 14:48:00')