python-定时任务-apschelduer
python-定时任务-apschelduer
1. apscheduler
1.1. install
pip install apscheduler
1.2. basic concepts
APScheduler has four kinds of components:
- triggers
- job stores
- executors
- schedulers
Your choice of scheduler depends mostly on your programming environment and what you’ll be using APScheduler for. Here’s a quick guide for choosing a scheduler:
- BlockingScheduler: use when the scheduler is the only thing running in your process
- BackgroundScheduler: use when 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 stores主要影响作业持久化,一般情况下使用默认方式default (MemoryJobStore)足够了,如果需要持久化,可能就得需要数据库支持了,例如SQLAlchemyJobStore。
exeutors主要有ThreadPoolExecutor,ProcessPoolExecutor,默认是前者,一般够用,除非是cpu密集型作业。
APScheduler comes with three built-in trigger types:
- date: use when you want to run the job just once at a certain point of time
- interval: use when you want to run the job at fixed intervals of time
- cron: use when you want to run the job periodically at certain time(s) of day
1.2.1. 示例
schedule.add_job(func=job1,trigger='interval', seconds=1)
schedule.add_job(func=job2, args=('lierl',), trigger='date', next_run_time=datetime.datetime.now()+datetime.timedelta(seconds=5))
schedule.add_job(func=job1, trigger='cron', month='1,3,5,7-9', day='*', hour='14', minute='*')
1.3. scheduler manage
scheduler.start()
scheduler.shutdown()
scheduler.pause()
This will cause the scheduler to not wake up until processing is resumed:
scheduler.resume()
It is also possible to start the scheduler in paused state, that is, without the first wakeup call:
scheduler.start(paused=True)
1.4. job administer add /remove/pause/resume/list/modify
There are two ways to add jobs to a scheduler:
- by calling add_job()
- by decorating a function with scheduled_job()
When you remove a job from the scheduler, it is removed from its associated job store and will not be executed anymore. There are two ways to make this happen:
- by calling remove_job() with the job’s ID and job store alias
- by calling remove() on the Job instance you got from add_job()
You can easily pause and resume jobs through either the Job instance or the scheduler itself. When a job is paused, its next run time is cleared and no further run times will be calculated for it until the job is resumed. To pause a job, use either method:
To resume:
获取当前任务列表
- get_jobs():It will return a list of Job instances. If you’re only interested in the jobs contained in a particular job store, then give a job store alias as the second argument.
- print_jobs():will print out a formatted list of jobs, their triggers and next run times.
2. 基本使用
2.1. 阻塞/非阻塞
下面是一个非阻塞型的定时任务调度。
#sys
import threading
import apscheduler
import time, datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.background import BackgroundScheduler
para = [1,2,3,4]
continue_run = True
def job1():
print('job1')
print(threading.current_thread())
print(time.strftime('%Y-%m-%d
%H:%M:%S', time.localtime()))
def job2(*args):
global para
print('job2', para)
print(threading.current_thread())
print(time.strftime('%Y-%m-%d
%H:%M:%S', time.localtime()))
def stop_runing():
global continue_run
continue_run = False
#sch = BlockingScheduler()
sch = BackgroundScheduler()
sch.add_job(job1, 'interval', seconds=5)
sch.add_job(job2, 'interval', seconds=8)
sch.add_job(stop_runing, 'date', run_date='2019-6-16
12:25:00',)
jl = sch.get_jobs() #[<Job
(id=66307271d51f451491fd7bf8e8ebfc47 name=job1)>, <Job
(id=af6ddd2c0ed94df58d889637cb7b816d name=job2)>]
sch.print_jobs()
print('main thread:', threading.current_thread())
print('before scheduler:', time.strftime('%Y-%m-%d
%H:%M:%S', time.localtime()))
sch.start()
while continue_run:
print('main')
time.sleep(10)
print('program ending.')
2.2.
执行时间问题
import threading
import apscheduler
import time, datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.background import BackgroundScheduler
continue_run = True
def aps_schduler():
para = [1,2,3,4]
def job1():
print('job1')
print(threading.current_thread())
print(time.strftime('%Y-%m-%d
%H:%M:%S', time.localtime()))
def job2(*args,
):
print('job2', args)
print(threading.current_thread())
print(time.strftime('%Y-%m-%d
%H:%M:%S', time.localtime()))
def stop_runing():
global continue_run
continue_run = False
#sch =
BlockingScheduler()
sch =
BackgroundScheduler()
# 添加定时任务
sch.add_job(job1, 'interval', seconds=5)
sch.add_job(job2, 'interval', seconds=8, args=['text'])
# 1分钟后执行stop_running
sch.add_job(stop_runing,
'date', run_date=time.strftime( '%Y-%m-%d
%H:%M:%S', time.localtime(time.time()+60)))
jl =
sch.get_jobs() #[<Job (id=66307271d51f451491fd7bf8e8ebfc47 name=job1)>,
<Job (id=af6ddd2c0ed94df58d889637cb7b816d name=job2)>]
sch.print_jobs()
print('main
thread:', threading.current_thread())
print('before
scheduler:', time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime()))
sch.start()
while continue_run:
print('main')
time.sleep(10)
print('program
ending.')
aps_schduler()
2.3.
超时问题
如果使用非阻塞模式,不存在超时问题,每次都会启一个新线程,直到达到max_instances给出的限制。
这里把实例限制设为1:
Execution of job
"aps_schduler.<locals>.job1 (trigger: interval[0:00:03], next run
at: 2019-06-16 16:19:35 CST)" skipped: maximum number of running instances
reached (1)
每次调度启动任务时冲突,会抛出一个异常信息,但不会终止执行;否则正常进行。
示例代码:
import threading
import apscheduler
import time, datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.background import BackgroundScheduler
continue_run = True
def aps_schduler():
para = [1,2,3,4]
count_x = 1
def job1():
nonlocal count_x
count_x +=1
print('job1')
print(threading.current_thread())
print(time.strftime('%Y-%m-%d
%H:%M:%S', time.localtime()))
time.sleep(15)
print(count_x)
def stop_runing():
global continue_run
continue_run = False
sch =
BackgroundScheduler()
# 添加定时任务
sch.add_job(job1, 'interval', seconds=3, max_instances=1)
# 1分钟后执行stop_running
sch.add_job(stop_runing,
'date', run_date=time.strftime( '%Y-%m-%d
%H:%M:%S', time.localtime(time.time()+60)))
print('main
thread:', threading.current_thread())
print('before
scheduler:', time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime()))
sch.start()
while continue_run:
print('main')
time.sleep(5)
print('program
ending.')
aps_schduler()
2.4.
首次执行时间问题
与twisted的定时任务类似,它也不会在一开始就执行;
除非指定:
sch.add_job(job1, 'interval', seconds=5, max_instances=1, next_run_time=datetime.datetime.now())
当然,在开始定时任务前手动执行一次也是可行的。
2.5.
其它设置
任务多实例
add_job有max_instances参数可以控制多任务实例
3.
api
3.1.
date apscheduler.triggers.date
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.start()
You can specify the exact time when the job should be run:
# The job will be executed
on November 6th, 2009 at 16:30:05
sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5), args=['text'])
The run date can be given as text too:
sched.add_job(my_job, 'date', run_date='2009-11-06 16:30:05', args=['text'])
To add a job to be run immediately:
# The 'date' trigger and
datetime.now() as run_date are implicit
sched.add_job(my_job, args=['text'])
4.
参考文档
参考文档:
https://apscheduler.readthedocs.io/en/latest/userguide.html#starting-the-scheduler
5.
testing code
5.1.
example1
import threading
import apscheduler
import time, datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.background import BackgroundScheduler
continue_run = True
def aps_schduler():
para = [1,2,3,4]
count_x = 1
def job1():
nonlocal count_x
count_x +=1
print('job1')
print(threading.current_thread())
print(time.strftime('%Y-%m-%d
%H:%M:%S', time.localtime()))
#time.sleep(15)
print(count_x)
def stop_runing():
global continue_run
continue_run = False
sch =
BackgroundScheduler()
# 添加定时任务
sch.add_job(job1, 'interval', seconds=5, max_instances=1, next_run_time=datetime.datetime.now())
# 1分钟后执行stop_running
sch.add_job(stop_runing,
'date', run_date=time.strftime( '%Y-%m-%d
%H:%M:%S', time.localtime(time.time()+60)))
print('main
thread:', threading.current_thread())
print('before
scheduler:', time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime()))
sch.start()
while continue_run:
#print('main')
time.sleep(5)
print('program
ending.')
aps_schduler()
python-定时任务-apschelduer的更多相关文章
- Python定时任务框架APScheduler 3.0.3 Cron示例
APScheduler是基于Quartz的一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以持久化任务.基 ...
- python 定时任务
Python 定时任务 最近学习到了 python 中两种开启定时任务的方法,和大家分享一下心得. sched.scheduler() threading.Timer() sched 定时任务 使用s ...
- Python定时任务框架APScheduler
http://blog.csdn.net/chosen0ne/article/details/7842421 APScheduler是基于Quartz的一个Python定时任务框架,实现了Quartz ...
- Python定时任务
在项目中,我们可能遇到有定时任务的需求.其一:定时执行任务.例如每天早上 8 点定时推送早报.其二:每隔一个时间段就执行任务.比如:每隔一个小时提醒自己起来走动走动,避免长时间坐着.今天,我跟大家分享 ...
- [Dynamic Language] Python定时任务框架
APScheduler是一个Python定时任务框架,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以持久化任务.并以daemon方式运行应用. 在APSchedu ...
- [转]Python定时任务框架APScheduler
APScheduler是基于Quartz的 一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以 持久化任务 ...
- Python 定时任务的实现方式
本文转载自: https://lz5z.com/Python%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%96% ...
- Python 定时任务框架 APScheduler 详解
APScheduler 最近想写个任务调度程序,于是研究了下 Python 中的任务调度工具,比较有名的是:Celery,RQ,APScheduler. Celery:非常强大的分布式任务调度框架 R ...
- python 定时任务APScheduler 使用介绍
python 定时任务APScheduler 使用介绍 介绍: APScheduler的全称是Advanced Python Scheduler.它是一个轻量级的 Python 定时任务调度框架. ...
- APScheduler(python 定时任务框架)最简单使用教程
有时候需要部署一些很简单的python定时任务,使用APScheduler是很好的选择.只需要简单的设置几个参数,就可以实现定时.定分甚至秒来跑. 第一步:用pip安装APScheduler pip ...
随机推荐
- 概率 lightoj 1027
题意 : 在n个门前选择一扇门出去, 然后如果第i扇门的 Xi值是正的话,你会花费Xi时间后出去 , 如果Xi是负数的话你会花费-Xi时间后回到老地方,并且忘记了刚才的选择, 选择一扇门的概率是等概的 ...
- 吴裕雄 python 机器学习——KNN回归KNeighborsRegressor模型
import numpy as np import matplotlib.pyplot as plt from sklearn import neighbors, datasets from skle ...
- 关于使用阿里云MAVEN镜像仓库
由于国内的某些不可明确的原因 国内连接google的时候十分慢,使得看github上的项目十分慢,这里我们可以修改build.gradle下的文件来使用阿里云仓库同步 会更快: // Top-leve ...
- SpringMVC的三种处理器适配器
SpringMVC具有三种处理器适配器,他们分别是BeanNameUrlHandlerMapping.SimpleControllerHandlerAdapter.ControllerClassNam ...
- 如何将博客内容输出到pdf
可以按照三类网页插件:Clearly,Instapaper 和 Readability,实际安装发现,第一个装不上,只有最后一个好用.在firefox或者chrom浏览器装好后,右键switch to ...
- laravel执行数据库迁移的过程中出现Illuminate\Database\QueryException : SQLSTATE[HY000] [2002] Operation timed out (SQL: select * from information_schema.tables where table_schema = shop and table_name = migrations
向customers表添加字段phone php artisan make:migration add_phone_to_customers_table 问题: 解决方法: 将DB_HOST配置项修改 ...
- NTP服务安装及时间同步
1.安装ntp服务命令 yum install -y ntp 2.常用NTP服务器地址: ntp1.aliyun.com ntp2.aliyun.com ntp3.aliyun.com ntp4.al ...
- C++(MFC)踩坑之旅 ------- 新建项目弹出“发生一个或多个错误”
结束隔离,回公司上班,把在家办公的程序考回公司的电脑,结果出错了,每当我新建项目时,都会弹出"发生一个或多个错误",点确定后回到新建项目的设置上面,折腾了两天时间才解决,以下是我的 ...
- Jmeter_JsonPath 提取器
1.登录老黄历 2.提取阳历的数据,不用正则表达式提取器,因为这里是字典形式,用Json path提取器更简单 3.把提取的数据放到百度里去发送请求 4. 5. 6. 7. 8. 9.
- 洛谷 P1063 能量项链(区间DP)
嗯... 题目链接:https://www.luogu.com.cn/problem/P1063 这道题首先要读懂题目,然后往上套区间dp,要转换成链式. AC代码: #include<cstd ...