APScheduler学习
说明
安装:
pip install apscheduler
首先来看一个周一到周五每天早上6点半喊我起床的例子:
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
# 输出时间
def job():
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# BlockingScheduler
scheduler = BlockingScheduler()
scheduler.add_job(job, 'cron', day_of_week='1-5', hour=6, minute=30)
scheduler.start()
APScheduler四个组件
触发器(trigger)
- date: 特定的时间点触发
- interval: 固定时间间隔触发
- cron: 在特定时间周期性地触发
作业存储(job store)
执行器(executor)
- ProcessPoolExecutor
- ThreadPoolExecutor
调度器(scheduler)
配置调度器
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime def job():
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# 定义BlockingScheduler
sched = BlockingScheduler()
sched.add_job(job, 'interval', seconds=5)
sched.start()
from datetime import datetime
from pymongo import MongoClient
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.jobstores.mongodb import MongoDBJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
# MongoDB 参数
host = '127.0.0.1'
port = 27017
client = MongoClient(host, port)
# 输出时间
def job():
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# 存储方式
jobstores = {
'mongo': MongoDBJobStore(collection='job', database='test', client=client),
'default': MemoryJobStore()
}
executors = {
'default': ThreadPoolExecutor(10),
'processpool': ProcessPoolExecutor(3)
}
job_defaults = {
'coalesce': False,
'max_instances': 3
}
scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
scheduler.add_job(job, 'interval', seconds=5, jobstore='mongo')
scheduler.start()

对 job 的操作
添加 job
- add_job()
- scheduled_job()
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
# 装饰器
@sched.scheduled_job('interval', id='my_job_id', seconds=5)
def job_function():
print("Hello World")
# 开始
sched.start()
移除 job
- remove_job()
- job.remove()
job = scheduler.add_job(myfunc, 'interval', minutes=2)
job.remove()
# id
scheduler.add_job(myfunc, 'interval', minutes=2, id='my_job_id')
scheduler.remove_job('my_job_id')
暂停和恢复 job
apscheduler.job.Job.pause()
apscheduler.schedulers.base.BaseScheduler.pause_job()
恢复一个 job:
apscheduler.job.Job.resume()
apscheduler.schedulers.base.BaseScheduler.resume_job()
希望你还记得 apscheduler.job.Job 是 add_job() 返回的实例
获取 job 列表
修改 job
job.modify(max_instances=6, name='Alternate name')
modify_job('my_job_id', trigger='cron', minute='*/5')
关闭 job
scheduler.shutdown()
scheduler.shutdown(wait=False)
scheduler 事件
def my_listener(event):
if event.exception:
print('The job crashed :(')
else:
print('The job worked :)')
# 添加监听器
scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
trigger 规则
date
- run_date (datetime|str) – the date/time to run the job at
- timezone (datetime.tzinfo|str) – time zone for run_date if it doesn’t have one already
from datetime import date
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
def my_job(text):
print(text)
# The job will be executed on November 6th, 2009
sched.add_job(my_job, 'date', run_date=date(2009, 11, 6), args=['text'])
sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5), args=['text'])
sched.add_job(my_job, 'date', run_date='2009-11-06 16:30:05', args=['text'])
# The 'date' trigger and datetime.now() as run_date are implicit
sched.add_job(my_job, args=['text'])
sched.start()
cron
- year (int|str) – 4-digit year
- month (int|str) – month (1-12)
- day (int|str) – day of the (1-31)
- week (int|str) – ISO week (1-53)
- day_of_week (int|str) – number or name of weekday (0-6 or mon,tue,wed,thu,fri,sat,sun)
- hour (int|str) – hour (0-23)
- minute (int|str) – minute (0-59)
- second (int|str) – second (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)
中文释义:
参数
|
说明
|
(int|str)
|
表示参数既可以是int类型,也可以是str类型
|
(datetime | str)
|
表示参数既可以是datetime类型,也可以是str类型
|
year(int or str)
|
年,4位数字
|
month(int or str)
|
月(范围1-12)
|
day(int or str)
|
日(范围1-31)
|
week(int or str)
|
周(范围1-53)
|
day_of_week(int or str)
|
周内第几天或者星期几(范围0-6或者mon,tue,wed,thu,fri,stat,sun)
|
hour(int or str)
|
时(0-23)
|
minute(int or str)
|
分(0-59)
|
second(int or str)
|
秒(0-59)
|
start_date(datetime or str)
|
最早开始日期(含)
|
end_date(datetime or str)
|
最晚结束日期(含)
|
timezone(datetime.tzinfo or str) | 指定时区 |
表达式:
示例:
from apscheduler.schedulers.blocking import BlockingScheduler def job_function():
print("Hello World")
# BlockingScheduler
sched = BlockingScheduler()
# Schedules job_function to be run on the third Friday
# of June, July, August, November and December at 00:00, 01:00, 02:00 and 03:00
sched.add_job(job_function, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3')
# Runs from Monday to Friday at 5:30 (am) until 2014-05-30 00:00:00
sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2014-05-30')
sched.start()
interval
- weeks (int) – number of weeks to wait
- days (int) – number of days to wait
- hours (int) – number of hours to wait
- minutes (int) – number of minutes to wait
- seconds (int) – number of seconds to wait
- start_date (datetime|str) – starting point for the interval calculation
- end_date (datetime|str) – latest possible date/time to trigger on
- timezone (datetime.tzinfo|str) – time zone to use for the date/time calculations
from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler def job_function():
print("Hello World")
# BlockingScheduler
sched = BlockingScheduler()
# Schedule job_function to be called every two hours
sched.add_job(job_function, 'interval', hours=2)
# The same as before, but starts on 2010-10-10 at 9:30 and stops on 2014-06-15 at 11:00
sched.add_job(job_function, 'interval', hours=2, start_date='2010-10-10 09:30:00', end_date='2014-06-15 11:00:00')
sched.start()
踩坑记录:
1、cron编写场景为每周五上午十点执行一次时,day_of_week字段为4,即当前星期数-1,也可以写成'fri'
文章来源:
APScheduler学习的更多相关文章
- 定时任务框架APScheduler学习详解
APScheduler简介 在平常的工作中几乎有一半的功能模块都需要定时任务来推动,例如项目中有一个定时统计程序,定时爬出网站的URL程序,定时检测钓鱼网站的程序等等,都涉及到了关于定时任务的问题,第 ...
- python 学习定时任务apscheduler模块
最近在解决定时任务问题找到了apscheduler模块,贴一段代码 from apscheduler.schedulers.blocking import BlockingSchedulerimpor ...
- 使用APScheduler启动Django服务时自动运行脚本(可设置定时运行)
Django搭建的服务器一般都用作WEB网站进行访问,通常的形式是用户访问网站或点击按钮发送请求,Django检测到请求后进行相应的试图函数处理后返回页面给用户. 但是,我们有时会需要有一些后台自动运 ...
- 全网最全的Windows下Anaconda2 / Anaconda3里正确下载安装用来定时任务apscheduler库(图文详解)
不多说,直接上干货! Anaconda2 里 PS C:\Anaconda2\Scripts> PS C:\Anaconda2\Scripts> pip.exe install apsc ...
- Python中定时任务框架APScheduler
前言 大家应该都知道在编程语言中,定时任务是常用的一种调度形式,在Python中也涌现了非常多的调度模块,本文将简要介绍APScheduler的基本使用方法. 一.APScheduler介绍 APSc ...
- 学习Python要知道哪些重要的库和工具
本文转自:https://github.com/jobbole/awesome-python-cn 环境管理 管理 Python 版本和环境的工具 p:非常简单的交互式 python 版本管理工具. ...
- Python中定时任务框架APScheduler的快速入门指南
前言 大家应该都知道在编程语言中,定时任务是常用的一种调度形式,在Python中也涌现了非常多的调度模块,本文将简要介绍APScheduler的基本使用方法. 一.APScheduler介绍 APSc ...
- 一个Python爬虫工程师学习养成记
大数据的时代,网络爬虫已经成为了获取数据的一个重要手段. 但要学习好爬虫并没有那么简单.首先知识点和方向实在是太多了,它关系到了计算机网络.编程基础.前端开发.后端开发.App 开发与逆向.网络安全. ...
- 从直播编程到直播教育:LiveEdu.tv开启多元化的在线学习直播时代
2015年9月,一个叫Livecoding.tv的网站在互联网上引起了编程界的注意.缘于Pingwest品玩的一位编辑在上网时无意中发现了这个网站,并写了一篇文章<一个比直播睡觉更奇怪的网站:直 ...
随机推荐
- HYSBZ 1036树链剖分
一棵树上有n个节点,编号分别为1到n,每个节点都有一个权值w.我们将以下面的形式来要求你对这棵树完成一些操作: I. CHANGE u t : 把结点u的权值改为t II. QMAX u v: 询问从 ...
- Python3 函数进阶2
目录 迭代器 可迭代对象 迭代器对象 总结和补充 列表推导式 字典生成式 zip()函数 递归 迭代器 迭代器是访问容器类数据类型元素的一种方式 迭代器是一个可以记住遍历的位置的对象 迭代器对象从容器 ...
- 小胖求学系列之-文档生成利器(下)-smart-doc
叮叮叮....一阵铃声响起,大家都陆续来到了课堂,看老师没来,小张和小胖又闲聊起来,小张问:怎么样,smart-doc好用吧.小胖笑着说:挺好用的,不过? 小张看卖关子,问到:不过什么,有什么新发现? ...
- PAT1057 Stack(树状数组+倍增)
目录 题目大意 题目分析 题目大意 要求维护一个栈,提供压栈.弹栈以及求栈内中位数的操作(当栈内元素\(n\)为偶数时,只是求第\(n/2\)个元素而非中间两数的平均值).最多操作100000次,压栈 ...
- 【Springboot】用Springboot Admin监控你的微服务应用
1 简介 目前,微服务大行其道,各大小公司争相学习模仿,把单体应用拆得七零八落.服务多了,运行的实例多了,给运维人员的压力就更大了.如果有十几个应用,单单做Health Check就已经够费时间的了. ...
- Another git process seems to be running in this repository
今天在推送项目的时候git突然报如题的错误.查了一下是由于git被另外一个程序占用,产生原 原因在于Git在使用过程中遭遇了崩溃,部分被上锁资源没有被释放. 解决方案也很简单,在git中找到对应的in ...
- C#mvc重新定向并在路径中使用html扩展名实现伪静态
首先修改配置文件,增加下面的两个配置: 接下来,修改MapRoute为路由增加.html后缀 完成后,我们来验证一下刚才的成果: http://localhost:2279/Home/.html 一个 ...
- git 本地代码 切换远程分支
公司之前代码使用的是gitlab,后来换成腾讯的工峰,所以需要切换远程不支,所以在原代码上切换即可. 在原项目打开git bash命令,打开后会显示本地的原始分支 打开后 添加新的远程分支,红色字体为 ...
- JS---案例:设置div的宽度
案例:设置div的宽度 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&qu ...
- oopday01(面向对象-类&private&this)
面向对象基本概述.封装 01_面向对象(面向对象思想概述) * A:面向过程思想概述 * 第一步 * 第二步 * B:面向对象思想概述 * 找对象(第一步,第二步) * C:举例 ...