APScheduler (advanceded python scheduler)是一款Python开发的定时任务工具

本文深入解析APScheduler的功能特性,包括其不依赖Linux系统的跨平台性、定时任务的持久化存储及动态添加能力。介绍四大核心组件:触发器、任务存储、执行人与调度者,以及如何配置和使用这些组件实现复杂的定时任务需求。

APScheduler

pip install apscheduler

1.特点

1.不依赖与linux系统,可以在不同的系统中运行,但是同样的定时任务:crontab依赖于Linux系统定时,独立运行。
2.对添加的定时任务可以持久保存(保存到数据库中)。
3.可以动态的添加定时任务

2.APScheduler 的四个组件

  • 1.1.触发器(triggers)
    date:当您想在某个特定时间点运行一次作业时使用
from datetime import date
# 在2019年11月6日00:00:00执行
sched.add_job(my_job, 'date', run_date=date(2009, 11, 6))
# 在2019年11月6日16:30:05
sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5))
sched.add_job(my_job, 'date', run_date='2009-11-06 16:30:05')
# 立即执行
sched.add_job(my_job, 'date')  
sched.start()

interval:当您想要以固定的时间间隔运行作业时使用

from datetime import datetime
# 每两小时执行一次
sched.add_job(job_function, 'interval', hours=2)
# 在2010年10月10日09:30:00 到2014年6月15日的时间内,每两小时执行一次
sched.add_job(job_function, 'interval', hours=2, start_date='2010-10-10 09:30:00', end_date='2014-06-15 11:00:00')
	

cron:当您想要在一天中的某个时间定期运行作业时使用

# 在6、7、8、11、12月的第三个周五的00:00, 01:00, 02:00和03:00 执行
sched.add_job(job_function, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')

# 在2014年5月30日前的周一到周五的5:30执行
sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2014-05-30')
	
  • 2.任务存储(job stores)
jobstores = {
	# 'default': SQLAlchemyJobStore(url='sqlite:///demo_1.sqlite')
	'default': SQLAlchemyJobStore(url='mysql://root:mysql@192.168.26.134/test')
		}
  • 3.任务执行人(executors)
    采用进程或者线程的方式都可以
executors = {
	# 使用多线程
    'default': ThreadPoolExecutor(max_workers=10)
    # 使用多进程
    'default': ProcessPoolExecutor(max_workers=5)
		}
  • 4.任务调度者(scheduler) 核心!!!!
一共有两种:
1. BackgroundScheduler

from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler(executors=executors, jobstores=jobstores)
scheduler.start()  # 此处程序会发生阻塞


2. BlockingScheduler

from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler(executors=executors, jobstores=jobstores)
scheduler.start()  # 此处程序不会发生阻塞

案例:

from apscheduler.schedulers.background import BlockingScheduler, BackgroundScheduler  # 调度器
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor  # 执行器
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore  # 存储器
# 1.创建任务函数
def my_apscheduler():
    print('working...')
# 2.创建执行器(使用线程)
executors = {
    'default': ThreadPoolExecutor(max_workers=5)
}
# 3.创建存储器(sqlite)
jobstores = {
    'default': SQLAlchemyJobStore(url='sqlite:///my_job.sqlite')
}
# 4.创建调度器(管理、执行、存储)
scheduler = BlockingScheduler(executors=executors, jobstores=jobstores)
# 5.添加任务(指定储发)
scheduler.add_job(my_apscheduler, 'interval', seconds=2)
# 6.开始调度器
scheduler.start()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值