apscheduler 指定隔多久开始法宝任务书可以换指定

1.安装  
pip install apscheduler
  安装完毕
2.&简单任务
  首先,来个最简单的例子,看看它的威力。
1 # coding:utf-8
2 from apscheduler.schedulers.blocking import BlockingScheduler
3 import datetime
6 def aps_test():
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '你好'
10 scheduler = BlockingScheduler()
11 scheduler.add_job(func=aps_test, trigger='cron', second='*/5')
12 scheduler.start()
  看代码,定义一个函数,然后定义一个scheduler类型,添加一个job,然后执行,就可以了,代码是不是超级简单,而且非常清晰。看看结果吧。
5秒整倍数,就执行这个函数,是不是超级超级简单?对了,apscheduler就是通俗易懂。
再写一个带参数的。
1 # coding:utf-8
2 from apscheduler.schedulers.blocking import BlockingScheduler
3 import datetime
6 def aps_test(x):
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x
9 scheduler = BlockingScheduler()
10 scheduler.add_job(func=aps_test, args=('你好',), trigger='cron', second='*/5')
11 scheduler.start()
结果跟上面一样的。
好了,上面只是给大家看的小例子,我们先从头到位梳理一遍吧。apscheduler分为4个模块,分别是Triggers,Job stores,Executors,Schedulers.从上面的例子我们就可以看出来了,triggers就是触发器,上面的代码中,用了cron,其实还有其他触发器,看看它的源码解释。
The ``trigger`` argument can either be:
#. the alias name of the trigger (e.g. ``date``, ``interval`` or ``cron``), in which case any extra keyword
arguments to this method are passed on to the trigger's constructor
#. an instance of a trigger class
看见没有,源码中解释说,有date, interval, cron可供选择,其实看字面意思也可以知道,date表示具体的一次性任务,interval表示循环任务,cron表示定时任务,好了,分别写个代码看看效果最明显。
1 # coding:utf-8
2 from apscheduler.schedulers.blocking import BlockingScheduler
3 import datetime
6 def aps_test(x):
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x
9 scheduler = BlockingScheduler()
10 scheduler.add_job(func=aps_test, args=('定时任务',), trigger='cron', second='*/5')
11 scheduler.add_job(func=aps_test, args=('一次性任务',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=12))
12 scheduler.add_job(func=aps_test, args=('循环任务',), trigger='interval', seconds=3)
14 scheduler.start()
其实应该不用我解释代码,大家也可以看出结果了,非常清晰。除了一次性任务,trigger是不要写的,直接定义next_run_time就可以了,关于date这部分,官网没有解释,但是去看看源码吧,看这行代码。
def _create_trigger(self, trigger, trigger_args):
if isinstance(trigger, BaseTrigger):
return trigger
elif trigger is None:
trigger = 'date'
elif not isinstance(trigger, six.string_types):
raise TypeError('Expected a trigger instance or string, got %s instead' % trigger.__class__.__name__)
# Use the scheduler's time zone if nothing else is specified
trigger_args.setdefault('timezone', self.timezone)
# Instantiate the trigger class
return self._create_plugin_instance('trigger', trigger, trigger_args)
第4行,如果trigger为None,直接定义trigger为'date'类型。其实弄到这里,大家应该自己拓展一下,如果实现web的异步任务。假设接到一个移动端任务,任务完成后,发送一个推送到移动端,用date类型的trigger完成可以做的很好。
  好了,scheduler的基本应用,我想大家已经会了,但这仅仅只是开始。如果代码有意外咋办?会阻断整个任务吗?如果我要计算密集型的任务咋办?下面有个代码,我们看看会发生什么情况。
1 # coding:utf-8
2 from apscheduler.schedulers.blocking import BlockingScheduler
3 import datetime
6 def aps_test(x):
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x
10 scheduler = BlockingScheduler()
11 scheduler.add_job(func=aps_test, args=('定时任务',), trigger='cron', second='*/5')
13 scheduler.start()
还是上面代码,但我们中间故意加了个错误,看看会发生什么情况。
说我们没有log文件,好吧,我们添加一个log文件,看看写的什么。
1 # coding:utf-8
2 from apscheduler.schedulers.blocking import BlockingScheduler
3 import datetime
4 import logging
6 logging.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.txt',
filemode='a')
13 def aps_test(x):
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x
17 scheduler = BlockingScheduler()
18 scheduler.add_job(func=aps_test, args=('定时任务',), trigger='cron', second='*/5')
19 scheduler._logger = logging
20 scheduler.start()
终于可以看到了,这时候才看到错误,这个是一定要注意的。
其实,到这里,完全可以执行大多数任务了,但我们为了效率,安全性,再往下面看看,还有什么。
4.删除任务
假设我们有个奇葩任务,要求执行一定阶段任务以后,删除某一个循环任务,其他任务照常进行。有如下代码:
1 # coding:utf-8
2 from apscheduler.schedulers.blocking import BlockingScheduler
3 import datetime
4 import logging
6 logging.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.txt',
filemode='a')
13 def aps_test(x):
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x
17 def aps_date(x):
scheduler.remove_job('interval_task')
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x
22 scheduler = BlockingScheduler()
23 scheduler.add_job(func=aps_test, args=('定时任务',), trigger='cron', second='*/5', id='cron_task')
24 scheduler.add_job(func=aps_date, args=('一次性任务,删除循环任务',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=12), id='date_task')
25 scheduler.add_job(func=aps_test, args=('循环任务',), trigger='interval', seconds=3, id='interval_task')
26 scheduler._logger = logging
28 scheduler.start()
看看结果,
在运行过程中,成功删除某一个任务,其实就是为每个任务定义一个id,然后remove_job这个id,是不是超级简单,直观?那还有什么呢?
5.停止任务,恢复任务
看看官方文档,还有pause_job, resume_job,用法跟remove_job一样,这边就不详细介绍了,就写个代码。
1 # coding:utf-8
2 from apscheduler.schedulers.blocking import BlockingScheduler
3 import datetime
4 import logging
6 logging.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.txt',
filemode='a')
13 def aps_test(x):
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x
17 def aps_pause(x):
scheduler.pause_job('interval_task')
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x
22 def aps_resume(x):
scheduler.resume_job('interval_task')
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x
26 scheduler = BlockingScheduler()
27 scheduler.add_job(func=aps_test, args=('定时任务',), trigger='cron', second='*/5', id='cron_task')
28 scheduler.add_job(func=aps_pause, args=('一次性任务,停止循环任务',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=12), id='pause_task')
29 scheduler.add_job(func=aps_resume, args=('一次性任务,恢复循环任务',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=24), id='resume_task')
30 scheduler.add_job(func=aps_test, args=('循环任务',), trigger='interval', seconds=3, id='interval_task')
31 scheduler._logger = logging
33 scheduler.start()
&是不是很容易?好了,删除任务,停止任务,恢复任务就介绍到这,下面我们看看监听任务。
任何代码都可能发生意外,关键是,发生意外了,如何第一时间知道,这才是公司最关心的,apscheduler已经为我们想到了这些。
看下面的代码,
1 # coding:utf-8
2 from apscheduler.schedulers.blocking import BlockingScheduler
3 from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
4 import datetime
5 import logging
7 logging.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.txt',
filemode='a')
14 def aps_test(x):
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x
18 def date_test(x):
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x
23 def my_listener(event):
if event.exception:
print '任务出错了!!!!!!'
print '任务照常运行...'
29 scheduler = BlockingScheduler()
30 scheduler.add_job(func=date_test, args=('一定性任务,会出错',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=15), id='date_task')
31 scheduler.add_job(func=aps_test, args=('循环任务',), trigger='interval', seconds=3, id='interval_task')
32 scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
33 scheduler._logger = logging
35 scheduler.start()
是不是很直观,在生产环境中,你可以把出错信息换成发送一封邮件或者发送一个短信,这样定时任务出错就可以立马就知道了。
  好了,今天就讲到这,以后我们有机会再来拓展这个apscheduler,这个非常强大而且直观的后台任务库。&
7作业运行的控制
add_job的第二个参数是trigger,它管理着作业的调度方式。它可以为date, interval或者cron。对于不同的trigger,对应的参数也相同。
(1). cron定时调度
year&(int|str) & 4-digit yearmonth&(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)和Linux的Crontab一样,它的值格式为:
Fire on every value
Fire every&a&values, starting from the minimum
Fire on any value within the&a-b&range (a must be smaller than b)
Fire every&c&values within the&a-b&range
Fire on the&x&-th occurrence of weekday&y&within the month
Fire on the last occurrence of weekday&x&within the month
Fire on the last day within the month
Fire on any can combine any number of any of the above expressions
几个例子如下:
# 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
sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='')
(2). interval 间隔调度
它的参数如下:weeks&(int) & number of weeks to waitdays&(int) & number of days to waithours&(int) & number of hours to waitminutes&(int) & number of minutes to waitseconds&(int) & number of seconds to waitstart_date&(datetime|str) & starting point for the interval calculationend_date&(datetime|str) & latest possible date/time to trigger ontimezone&(datetime.tzinfo|str) & time zone to use for the date/time calculations例子:
# Schedule job_function to be called every two hours
sched.add_job(job_function, 'interval', hours=2)
(3). date 定时调度
最基本的一种调度,作业只会执行一次。它的参数如下:run_date&(datetime|str) & the date/time to run the job attimezone&(datetime.tzinfo|str) & time zone for run_date if it doesn&t have one already例子:
# The job will be executed on November 6th, 2009
sched.add_job(my_job, 'date', run_date=date(2009, 11, 6), args=['text'])
# 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'])
&7.Flask-APScheduler使用
https://www.jianshu.com/p/c
https://www.cnblogs.com/yueerwanwan0204/p/5480870.html
http://debugo.com/apscheduler/
阅读(...) 评论()
levels of contents在 SegmentFault,学习技能、解决问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。
问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
使用apscheduler定时执行多个任务,有的任务某个时间点执行一次,有的任务每隔一段时间执行一次;添加任务的时候使用scheduled_job装饰器,没有使用add_job方法;
现在的问题是,启动apscheduler所有的定时任务后,过一段时间,apscheduler的任务会自动重启,导致那些定点执行一次的任务没有执行完成;
执行定时任务的过程中涉及mysql查询操作,其中mysql有主从库;
从日志中查看,当定时任务查询主库的时候,apscheduler任务不会重启;而访问从库的时候,程序会重新连接数据库,定时任务就会重新加载;
难道重连mysql会导致定时任务重启????
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
添加misfire_grace_time的参数
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
misfire_grace_time
这个参数的前提是使用可持续化的jobstore,如果使用默认内存的jobstore,这个参数是没有意义的。
一般需要使用misfire_grace_time的场景,就是但是那个持久化jobstore的服务挂掉了,任务需要被调度的时候没有被调度成功,后期持久化的jobstore启动了,这个任务重新被调度了(从jobstore中获取job),misfire_grace_time决定这个任务在错过执行时间之后还需不需要执行
分享到微博?
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
我要该,理由是:
在 SegmentFault,学习技能、解决问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。APScheduler执行定时任务---简单使用
本例目的:每天17:19:07打印 hello scheduler
1.下载源码
2.解压、安装
tar -zxvf 源码包名
python setup.py install
3.简单使用:
from apscheduler.schedulers.blocking import BlockingScheduler
schedudler = BlockingScheduler()
def worker()
print "hello scheduler"
schedudler.add_job(capture_Timer,'cron',day_of_week ='0-7',hour = 17,minute = 19,second = 07)
schedudler.start()
除此之外,还有更厉害的,请见:
acs安装记录
第一次python setup.py install 后失败,现象,python窗口import相关包时报错,有找不到的模块;
再执行一次python setup.py install ,观察到在下载相关依赖,后import成功。
没有更多推荐了,
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!APScheduler基本使用
APScheduler库基础学习
APScheduler组成组件
触发器,有自己的任务调度逻辑,每一个job单位都有触发器决定下一次何时运行。除了初始化的配置,他没有状态。
Job stores
储存调度任务,默认job对象,是储存在内存中,也可以用其他job对象把他们储存在各种数据库中;job保存到持久化仓库时,job数据要进行序列化,当加载job时也要进行反序列化。Job不能共享调度器。
是job运行的处理器,通常通过提交指定调用的job到进程或者线程池处理;当job完成后,通知发出一个适当的事件调度程序。
Schedulers
通常一个应用只有一个调度器,schdeuler开发者不直接处理jobs stores、Executors、Triggers, 相反,调度程序提供适当的接口来处理这些;配置job stores和executors通过调度器来完成,如增加,删除和修改。
APScheduler常用调度器
BlockingScheduler: 当应用程序中只有调度器时使用。
BackgroundScheduler: 不使用任何以下框架(asyncio、gevent、Tornado、Twisted、Qt),并且需要在你的应用程序后台运行调度程序
AsyncIOScheduler: 应用程序使用asyncio模块时使用
GeventScheduler: 应用程序使用gevent模块时使用
TornadoScheduler: Tornado应用程序时使用
TwistedScheduler: Twisted应用程序使用
QtScheduler: Qt应用程序时使用
APScheduler触发器
DateTrigger——日期触发器
添加此类触发器job之后,只运行一次,可以指定运行时间;若不指定则默认为当前时间。
正常使用时,使用add_job,不指定trigger类型,默认就是DateTrigger
指定trigger类型,可以使用字符串date,或者直接使用类DateTrigger的实例
from apscheduler.triggers.date import DateTrigger
scheduler.add_job(date_tick)
scheduler.add_job(date_tick, 'date')
date = DateTrigger(datetime.now()+dt.timedelta(seconds=120))
scheduler.add_job(date_tick, date)
IntervalTrigger——间隔触发器
此触发器,可以指定开始时间start_date,结束时间end_date,以及间隔时间,
间隔时间可以有weeks/days/hours/minutes/seconds组成,
开始时间之后,每隔多少interval执行一次任务,直至结束时间,如果不指定结束时间,则一直执行
指定此类触发器类型,可以使用字符串interval,也可以使用类IntervalTrigger的实例对象
from apscheduler.triggers.interval import IngervalTrigger
scheduler.add_job(interval_tick,'interval',seconds=4,minutes=2,
start_date=datetime.now()+dt.timedelta(seconds=120),
end_date=datetime.now()+dt.timedelta(seconds=360))
trigger = IntervalTrigger(seconds=60,
start_date=datetime.now()+dt.timedelta(seconds=60),
end_date=datetime.now() + dt.timedelta(seconds=120))
scheduler.add_job(date_tick, trigger)
CronTrigger——Cron触发器
类Unix系统中的Cron中,可以任意配置指定,年月日时分秒,周,每周几定时处理任务
由表达式(Expression)和字段(Field)组成,可以根据每个字段的表达式获取执行值,由调度器获取具体的执行日期
year’: ‘‘, ‘month’: 1, ‘day’: 1, ‘week’: ‘‘, ‘day_of_week’: ‘*’, ‘hour’: 0, ‘minute’: 0, ‘second’: 0
指定具体值,或者每分钟,或者每几分钟,或者每周几等当时
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)
Expression
Description
Fire on every value
Fire every a values, starting from the minimum
Fire on any value within the a-b range (a must be smaller than b)
Fire every c values within the a-b range
Fire on the x-th occurrence of weekday y within the month
Fire on the last occurrence of weekday x within the month
Fire on the last day within the month
Fire on any can combine any number of any of the above expressions
没有更多推荐了,
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!Posts - 99,
Articles - 0,
Comments - 2
Proficient in Programming,
Understand in design,
Good at operating,
Know the process.
14:52 by linkxu, ... 阅读,
APScheduler是python下的任务调度框架,全程为Advanced Python Scheduler,是一款轻量级的Python任务调度框架。它允许你像Linux下的Crontab那样安排定期执行的任务,并且支持Python函数或任意可调用的对象。
(ENV1) [eason@localhost]$ pip install apscheduler
Collecting apscheduler
Downloading APScheduler-3.3.0-py2.py3-none-any.whl (57kB)
100% |████████████████████████████████| 61kB 81kB/s
Collecting pytz (from apscheduler)
Downloading pytz-2016.10-py2.py3-none-any.whl (483kB)
100% |████████████████████████████████| 491kB 52kB/s
C python_version == "2.7" (from apscheduler)
Downloading funcsigs-1.0.2-py2.py3-none-any.whl
Requirement already satisfied: six&=1.4.0 in /home/eason/ENV1/lib/python2.7/site-packages (from apscheduler)
Collecting tzlocal&=1.2 (from apscheduler)
Downloading tzlocal-1.3.tar.gz
Requirement already satisfied: setuptools&=0.7 in /home/eason/ENV1/lib/python2.7/site-packages (from apscheduler)
C python_version == "2.7" (from apscheduler)
Downloading futures-3.0.5-py2-none-any.whl
Building wheels for collected packages: tzlocal
Running setup.py bdist_wheel for tzlocal ... done
Stored in directory: /home/eason/.cache/pip/wheels/80/19/a8/635ad9f4ad8a63b49d073c55cbca31fbed145a69
Successfully built tzlocal
Installing collected packages: pytz, funcsigs, tzlocal, futures, apscheduler
Successfully installed apscheduler-3.3.0 funcsigs-1.0.2 futures-3.0.5 pytz-2016.10 tzlocal-1.3
(ENV1) [eason@localhost]$
APScheduler 有四种组件:
job stores
schedulers
triggers(触发器)中包含调度逻辑,每个作业都由自己的触发器来决定下次运行时间。除了他们自己初始配置意外,触发器完全是无状态的。
job stores(作业存储器)存储被调度的作业,默认的作业存储器只是简单地把作业保存在内存中,其他的作业存储器则是将作业保存在数据库中。当作业被保存到一个持久化的作业存储器中的时候,该作业的数据会被序列化,并在加载时被反序列化。作业存储器不能共享调度器。
executors(执行器)处理作业的运行,他们通常通过在作业中提交指定的可调用对象到一个线程或者进城池来进行。当作业完成时,执行器将会通知调度器。
schedulers(调度器)配置作业存储器和执行器可以在调度器中完成,例如添加、修改和移除作业。根据不同的应用场景可以选用不同的调度器,可选的有BlockingScheduler,BackgroundScheduler,AsyncIOScheduler,GeventScheduler,TornadoScheduler,TwistedScheduler,QtScheduler 7种。
选择合适的调度器
BlockingScheduler : 当调度器是你应用中唯一要运行的东西时
BackgroundScheduler : 当你没有运行任何其他框架并希望调度器在你应用的后台执行时使用。
AsyncIOScheduler : 当你的程序使用了asyncio(一个异步框架)的时候使用。
GeventScheduler : 当你的程序使用了gevent(高性能的Python并发框架)的时候使用。
TornadoScheduler : 当你的程序基于Tornado(一个web框架)的时候使用。
TwistedScheduler : 当你的程序使用了Twisted(一个异步框架)的时候使用
QtScheduler : 如果你的应用是一个Qt应用的时候可以使用。
选择合适的作业存储器
如果你的应用在每次启动的时候都会重新创建作业,那么使用默认的作业存储器(MemoryJobStore)即可,但是如果你需要在调度器重启或者应用程序奔溃的情况下任然保留作业,你应该根据你的应用环境来选择具体的作业存储器。例如:使用Mongo或者SQLAlchemy JobStore (用于支持大多数RDBMS)
关于执行器
对执行器的选择取决于你使用上面哪些框架,大多数情况下,使用默认的ThreadPoolExecutor已经能够满足需求。如果你的应用涉及到CPU密集型操作,你可以考虑使用ProcessPoolExecutor来使用更多的CPU核心。你也可以同时使用两者,将ProcessPoolExecutor作为第二执行器。
关于触发器
当你调度作业的时候,你需要为这个作业选择一个触发器,用来描述这个作业何时被触发,APScheduler有三种内置的触发器类型:
date&一次性指定日期
interval&在某个时间范围内间隔多长时间执行一次
cron&和Linux crontab格式兼容,最为强大
date&最基本的一种调度,作业只会执行一次。它的参数如下:
run_date&(datetime|str) & 作业的运行日期或时间
timezone&(datetime.tzinfo|str) & 指定时区
举个栗子:
interval&间隔调度,参数如下:
weeks (int)&& 间隔几周
days (int)&& 间隔几天
hours (int)&& 间隔几小时
minutes (int)&& 间隔几分钟
seconds (int)&& 间隔多少秒
start_date (datetime|str)&& 开始日期
end_date (datetime|str)&& 结束日期
timezone (datetime.tzinfo|str)&& 时区
举个栗子:
cron参数如下:
year&(int|str) & 年,4位数字
month&(int|str) & 月 (范围1-12)
day&(int|str) & 日 (范围1-31)
week&(int|str) & 周 (范围1-53)
day_of_week&(int|str) & 周内第几天或者星期几 (范围0-6 或者 mon,tue,wed,thu,fri,sat,sun)
hour&(int|str) & 时 (范围0-23)
minute&(int|str) & 分 (范围0-59)
second&(int|str) & 秒 (范围0-59)
start_date&(datetime|str) & 最早开始日期(包含)
end_date&(datetime|str) & 最晚结束时间(包含)
timezone&(datetime.tzinfo|str) & 指定时区
取值格式:
表达式参数描述
Fire on every value
Fire every a values, starting from the minimum
Fire on any value within the a-b range (a must be smaller than b)
Fire every c values within the a-b range
Fire on the x -th occurrence of weekday y within the month
Fire on the last occurrence of weekday x within the month
Fire on the last day within the month
Fire on any can combine any number of any of the above expressions
举个栗子:
添加作业有两种方法,一种是使用add_job()函数,还有一种方式是通过scheduled_job()装饰器。
add_job()函数方式
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
def my_job1():
print 'my_job1 is running, Now is %s' % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def my_job2():
print 'my_job2 is running, Now is %s' % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
sched = BlockingScheduler()
执行结果:
$my_job2 is running, Now is 2016-12-13 14:41:10
$my_job1 is running, Now is 2016-12-13 14:41:12
$my_job2 is running, Now is 2016-12-13 14:41:15
$my_job1 is running, Now is 2016-12-13 14:41:17
$my_job2 is running, Now is 2016-12-13 14:41:20
$my_job1 is running, Now is 2016-12-13 14:41:22
$my_job2 is running, Now is 2016-12-13 14:41:25
$my_job1 is running, Now is 2016-12-13 14:41:27
scheduled_job()装饰器方式
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
sched = BlockingScheduler()
执行结果:
$my_job2 is running, Now is 2016-12-13 15:09:00
$my_job1 is running, Now is 2016-12-13 15:09:03
$my_job2 is running, Now is 2016-12-13 15:09:05
$my_job1 is running, Now is 2016-12-13 15:09:08
$my_job2 is running, Now is 2016-12-13 15:09:10
$my_job1 is running, Now is 2016-12-13 15:09:13
$my_job2 is running, Now is 2016-12-13 15:09:15
$my_job1 is running, Now is 2016-12-13 15:09:18
使用SQLAlchemy作业存储器存放作业
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime,timedelta
import logging
sched = BlockingScheduler()
def my_job():
print 'my_job is running, Now is %s' % datetime.now().strftime("%Y-%m-%d %H:%M:%S")
执行结果:
$ python scheduler.py
INFO:apscheduler.executors.default:Running job "my_job (trigger: interval[0:00:05], next run at:
21:26:45 CST)" (scheduled at 2016-12-13 21:26:45.067157+08:00)
my_job is running, Now is 2016-12-13 21:26:45
INFO:apscheduler.executors.default:Job "my_job (trigger: interval[0:00:05], next run at:
21:26:50 CST)" executed successfully
INFO:apscheduler.executors.default:Running job "my_job (trigger: interval[0:00:05], next run at:
21:26:50 CST)" (scheduled at 2016-12-13 21:26:50.067157+08:00)
my_job is running, Now is 2016-12-13 21:26:50
INFO:apscheduler.executors.default:Job "my_job (trigger: interval[0:00:05], next run at:
21:26:50 CST)" executed successfully
INFO:apscheduler.executors.default:Running job "my_job (trigger: interval[0:00:05], next run at:
21:26:55 CST)" (scheduled at 2016-12-13 21:26:55.067157+08:00)
my_job is running, Now is 2016-12-13 21:26:55
INFO:apscheduler.executors.default:Job "my_job (trigger: interval[0:00:05], next run at:
21:26:55 CST)" executed successfully
INFO:apscheduler.executors.default:Running job "my_job (trigger: interval[0:00:05], next run at:
21:27:00 CST)" (scheduled at 2016-12-13 21:27:00.067157+08:00)
my_job is running, Now is 2016-12-13 21:27:00
INFO:apscheduler.executors.default:Job "my_job (trigger: interval[0:00:05], next run at:
21:27:05 CST)" executed successfully
INFO:apscheduler.executors.default:Running job "my_job (trigger: interval[0:00:05], next run at:
21:27:05 CST)" (scheduled at 2016-12-13 21:27:05.067157+08:00)
my_job is running, Now is 2016-12-13 21:27:05
INFO:apscheduler.executors.default:Job "my_job (trigger: interval[0:00:05], next run at:
21:27:05 CST)" executed successfully}

我要回帖

更多关于 apscheduler 多个任务 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信