1、BackgroundScheduler:在不使用以下任何框架且希望调度程序在应用程序内部的后台运行时使用
2、只需调用start()调度程序即可启动调度 程序。对于除以外的调度程序BlockingScheduler,此调用将立即返回,您可以继续应用程序的初始化过程,可能会向调度程序添加作业。
2、注意: 调度程序启动后,您将无法再更改其设置。
# 代码
from datetime import datetime
import os
import logging
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
basicConfig = {"level": logging.INFO, "format": "%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s",
"datefmt": '%Y-%m-%d %H:%M:%S', "filename": 'log1.BlockingScheduler', "filemode": "a"}
kwargs={
'apscheduler.jobstores.default': {
'type': 'sqlalchemy',
'url': 'postgres://postgres:123456@127.0.0.1:5433/postgres'
},
'apscheduler.executors.default': {
'class': 'apscheduler.executors.pool:ThreadPoolExecutor',
'max_workers': '20'
},
'apscheduler.executors.processpool': {
'type': 'processpool',
'max_workers': '5'
},
'apscheduler.job_defaults.coalesce': 'false',
'apscheduler.job_defaults.max_instances': '3',
'apscheduler.timezone': 'Asia/Shanghai', # 设置时区 ,存储桶时区
}
def my_listener(event):
if event.exception:
print('任务出错了!!!!!!')
else:
print('任务照常运行...')
def tick():
print('Tick! The time is: %s' % datetime.now())
if __name__ == '__main__':
logging.basicConfig(**basicConfig)
scheduler = BlockingScheduler(kwargs)
scheduler.add_job(tick, 'interval', seconds=3)
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
scheduler._logger = logging
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass