APscheduler总结
APscheduler使用总结
APscheduler是执行定时任务的python库,其作用可以代替Linux系统下的crontab,github上有该库的例子。
APsheduler基本使用
该模块由4个基本组件组成:
- triggers 触发器
- job stores 任务储存
- executors 执行器
- schedulers 调度器
其中triggers定义了定时任务的类别、触发条件以及具体要执行的任务名。
job stores可以将任务储存起来,有些需要重复执行的任务,或有数据生成的任务,有将数据储存的要求,可以通过数据库或文件的形式将数据储存起来以便下次使用。
executors负责具体的任务执行。
schedulers是最高级的组件,负责其它的管理和调度工作,该模块有几种可选的调度器可供选择,使用方法都是一样的:
BlockingScheduler: use when the scheduler is the only thing running in your process
BackgroundScheduler: use then you’re not using any of the frameworks below, and want the scheduler to run in the background inside your application
AsyncIOScheduler: use if your application uses the asyncio module
GeventScheduler: use if your application uses gevent
TornadoScheduler: use if you’re building a Tornado application
TwistedScheduler: use if you’re building a Twisted application
QtScheduler: use if you’re building a Qt application
定时任务的执行内容放在一个函数中使用,而调度的类型和时间等设置则在创建这个job的时候进行定义,在这个模块中,一个具体的任务是一个JOB实例,因此可以通过修改这个实例的属性对任务进行重新设置,而每一个job实例都是依赖于一个scheduler,所以也可以通过sheduler对sheduler进行重新设定。
定时任务的类型说明
参考源码中scheduler.add_job()的参数说明
'cron'跟linux下crontab一样的定时类型写法,
'interval'使用时间间隔的写法
...
说明
from apscheduler.schedulers.background import BackgroundScheduler
# 创建scheduler
scheduler = BackgroundScheduler()
# 创建job
# 方法1
job = scheduler.add_job(myfunc, 'interval', minutes=2, id='my_job_id')
# 方法2
@scheduler.scheduled_job
def myfunc():
# do something
pass
# 启动
scheduler.start()
# 添加job
scheduler.add_job(myfunc, 'interval', minutes=2, id='my_job_id')
# 删除job
scheduler.remove_job('my_job_id')
# 暂停job
scheduler.pause_job()
# 恢复job
scheduler.resume_job()
# 查看jobs
scheduler.get_jobs()
scheduler.print_jobs()
# 修改job
scheduler.modify_job(max_instances=6, name='Alternate name')
# 重新设置定时任务类型
scheduler.reschedule_job('my_job_id', trigger='cron', minute='*/5')
# 关闭
scheduler.shutdown(wait=False)
scheduler配置
配置内容
- a MongoDBJobStore named “mongo”
- an SQLAlchemyJobStore named “default” (using SQLite)
- a ThreadPoolExecutor named “default”, with a worker count of 20
- a ProcessPoolExecutor named “processpool”, with a worker count of 5
- utc标准时区
- coalescing turned off for new jobs by default
- 默认最多3个jobs
方法1
from pytz import utc
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.mongodb import MongoDBJobStore
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
jobstores = {
'mongo': MongoDBJobStore(),
'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
executors = {
'default': ThreadPoolExecutor(20),
'processpool': ProcessPoolExecutor(5)
}
job_defaults = {
'coalesce': False,
'max_instances': 3
}
scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)
方法2
from apscheduler.schedulers.background import BackgroundScheduler
# The "apscheduler." prefix is hard coded
scheduler = BackgroundScheduler({
'apscheduler.jobstores.mongo': {
'type': 'mongodb'
},
'apscheduler.jobstores.default': {
'type': 'sqlalchemy',
'url': 'sqlite:///jobs.sqlite'
},
'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': 'UTC',
})
方法3
from pytz import utc
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ProcessPoolExecutor
jobstores = {
'mongo': {'type': 'mongodb'},
'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
executors = {
'default': {'type': 'threadpool', 'max_workers': 20},
'processpool': ProcessPoolExecutor(max_workers=5)
}
job_defaults = {
'coalesce': False,
'max_instances': 3
}
scheduler = BackgroundScheduler()
# .. do something else here, maybe add jobs etc.
scheduler.configure(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)
flask下使用APscheduler
flask下使用该模块可以使用flask扩展模块flask-apsheduler
基本使用
from flask import Flask
from flask_apscheduler import APScheduler
class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'jobs:job1',
'args': (1, 2),
'trigger': 'interval',
'seconds': 10
}
]
SCHEDULER_API_ENABLED = True
def job1(a, b):
print(str(a) + ' ' + str(b))
if __name__ == '__main__':
app = Flask(__name__)
app.config.from_object(Config())
scheduler = APScheduler()
# it is also possible to enable the API directly
# scheduler.api_enabled = True
scheduler.init_app(app)
scheduler.start()
app.run()
故障排除
在使用gunicorn对flask进行管理的时候如何保证只定时任务只启动一次
问题在使用gunicorn对flask应用进行控制的时候如果设置了gunicorn的--worker参数大于1时,会出现一个定时任务执行多次的问题,此时要给gunicorn提供一个额外的--preload参数,这样,flask的app在run之前的所有操作只会执行一次,因此定时任务就只会执行一次。
env/bin/gunicorn module_containing_app:app -b 0.0.0.0:8080 --workers 3 --preload
flask在调试模式下调用flask-apscheduler定时任务时会执行多次
问题与上面的问题类似,调试模式下只需给app.run()添加一个参数use_reloader即可。
app.run(debug=True, use_reloader=False)
APscheduler总结的更多相关文章
- Python任务调度模块 – APScheduler
APScheduler是一个Python定时任务框架,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以持久化任务.并以daemon方式运行应用.目前最新版本为3.0 ...
- python3使用pyinstaller打包apscheduler出的错
本来只是想用Python做一个定时任务小工具在服务器上运行,可是服务器在隔离区,各种禁止上外网,使用pip导出列表那种下载库的方法不管用,导致Python的各种库都下不到,官网离线下载又各种缺依赖,好 ...
- Python定时任务框架APScheduler 3.0.3 Cron示例
APScheduler是基于Quartz的一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以持久化任务.基 ...
- apscheduler 绿色版
由于依赖EntryPoint,因此apscheduler在离线的方式(直接拷贝然后引用)使用时,会报错. 错误信息类似: No trigger by the name “interval/cron/d ...
- apscheduler 排程
https://apscheduler.readthedocs.org/en/v2.1.2/cronschedule.html 参数 说明 year 4位年 month 月份1-12 day 日:1- ...
- APScheduler —— Python化的Cron
APScheduler全程为Advanced Python Scheduler,是一款轻量级的Python任务调度框架.它允许你像Cron那样安排定期执行的任务,并且支持Python函数或任意可调用的 ...
- apscheduler的使用
最近一个程序要用到后台定时任务,看了看python后台任务,一般2个选择,一个是apscheduler,一个celery.apscheduler比较直观简单一点,就选说说这个库吧.网上一搜索,晕死,好 ...
- 定时任务框架APScheduler学习详解
APScheduler简介 在平常的工作中几乎有一半的功能模块都需要定时任务来推动,例如项目中有一个定时统计程序,定时爬出网站的URL程序,定时检测钓鱼网站的程序等等,都涉及到了关于定时任务的问题,第 ...
- django-xadmin中APScheduler的启动初始化
环境: python3.5.x + django1.9.x + xadmin-for-python3 APScheduler做为一个轻量级和使用量很多的后台任务计划(scheduler)包,可以方便 ...
- flask+apscheduler+redis实现定时任务持久化
在我们开发flask的时候,我们会结合apscheduler实现定时任务,我们部署到服务器上,会不会遇到这样的问题,每次我们部署后,我们重启服务后,原来的定时任务都需要重启,这样对我们经常迭代的项目肯 ...
随机推荐
- TouTiao开源项目 分析笔记4==>一个简单APP 整体常用框架
1.效果预览 1.1.如下图所以,到目前为止所有的功能. 2.从InitApp开始->SplashActivity->MainActivity 2.1.InitApp源代码.这是整个项目的 ...
- 51Nod 1680 区间求和 树状数组
题意: 给出一个长度为\(n\)的数列\(A_i\),定义\(f(k)\)为所有长度大于等于\(k\)的子区间中前\(k\)大数之和的和. 求\(\sum_{k=1}^{n}f(k) \; mod \ ...
- java 1.7 新io 实践 NIO2
Files 类使用 package com.xinyu.test; import java.io.IOException; import java.nio.ByteBuffer; import jav ...
- Oracle 学习----:Oracle删除表时报错:表或视图不存在
表明明存在,但是删除时却报错:表或视图不存在. 可能的原因之一是表名包含了小写,可以用双引号包含表名通过drop命令来删除, 如下所示: drop table "tmp_ST" ; ...
- python学习_循环结构 and 类型判断
# 循环结构 ### 循环结构(while) - 格式 ```python while 表达式: 语句块 ``` > 执行流程:当程序执行到while语句时,首先判断表达式的真假.若表达式的值为 ...
- 孤荷凌寒自学python第五天初识python的列表
孤荷凌寒自学python第五天 列表 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 粗俗地区分列表,可以这样理解,定义或print列表后显示时,列表中的各元素都是用一个方括号[]括起来的. ...
- Hadoop平台K-Means聚类算法分布式实现+MapReduce通俗讲解
Hadoop平台K-Means聚类算法分布式实现+MapReduce通俗讲解 在Hadoop分布式环境下实现K-Means聚类算法的伪代码如下: 输入:参数0--存储样本数据的文本文件inpu ...
- Java 以及JEE环境快速搭建
吐槽一下 博主最近找了一个Java Development的实习,加上上个月末的考试周,所以很久没有更新博客. 上了一周的班,还没有在熟悉项目的阶段. 感想:哇,读别人的代码是一件很费力的事情啊!!! ...
- 史林枫:sqlserver数据库中数据日志的压缩及sqlserver占用内存管理设置
使用sqlserver和IIS开发.net B/S程序时,数据量逐渐增多,用户也逐渐增多,那么服务器的稳定性就需要维护了.数据库如何占用更小内存,无用的日志如何瞬间清空? 今天在给一个客户维护网站的时 ...
- Linux下性能测量和调试诊断工具Systemtap
一.简介 SystemTap是一个诊断Linux系统性能或功能问题的开源软件.它使得对运行时的Linux系统进行诊断调式变得更容易.更简单.有了它,开发者或调试人员不再需要重编译.安装新内核.重启动等 ...