APScheduler提供了许多不同的方式来配置调度器,你可以使用一个配置字典或者作为参数关键字的方式传入。你也可以先创建调度器,再配置和添加作业,这样你可以在不同的环境中得到更大的灵活性。 下面是一个简单使用BlockingScheduler,并使用默认内存存储和默认执行器。(默认选项分别是MemoryJobStore和ThreadPoolExecutor,其中线程池的最大线程数为10)。配置完成后使用start()方法来启动。
from apscheduler.schedulers.blocking import BlockingScheduler def my_job(): print 'hello world' sched = BlockingScheduler() sched.add_job(my_job, 'interval', seconds=5) sc 1 from apscheduler.schedulers.blocking import BlockingScheduler 2 def my_job(): 3 print 'hello world' 4 5 sched = BlockingScheduler() 6 sched.add_job(my_job, 'interval', seconds=5) 7 sched.start()
在运行程序5秒后,将会输出第一个Hello world。 下面进行一个更复杂的配置,使用两个作业存储和两个调度器。在这个配置中,作业将使用mongo作业存储,信息写入到MongoDB中。
from pymongo import MongoClient from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.jobstores.mongodb import MongoDBJobStore from apscheduler.jobstores.memory import MemoryJobStore from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor def my_job(): print 'hello world' host = '127.0.0.1' port = 27017 client = MongoClient(host, port) 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(my_job, 'interval', seconds=5) try: scheduler.start() except SystemExit: client.close 1 from pymongo import MongoClient 2 from apscheduler.schedulers.blocking import BlockingScheduler 3 from apscheduler.jobstores.mongodb import MongoDBJobStore 4 from apscheduler.jobstores.memory import MemoryJobStore 5 from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor 6 7 8 def my_job(): 9 print 'hello world' 10 host = '127.0.0.1' 11 port = 27017 12 client = MongoClient(host, port) 13 14 jobstores = { 15 'mongo': MongoDBJobStore(collection='job', database='test', client=client), 16 'default': MemoryJobStore() 17 } 18 executors = { 19 'default': ThreadPoolExecutor(10), 20 'processpool': ProcessPoolExecutor(3) 21 } 22 job_defaults = { 23 'coalesce': False, 24 'max_instances': 3 25 } 26 scheduler = BlockingScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults) 27 scheduler.add_job(my_job, 'interval', seconds=5) 28 29 try: 30 scheduler.start() 31 except SystemExit: 32 client.close()
查询MongoDB可以看到作业的运行情况如下:
{ "_id" : "55ca54ee4bb744f8a5ab08cc4319bc24", "next_run_time" : 1434017278.797, "job_state" : new BinData(0, "gAJ9cQEoVQRhcmdzcQIpVQhleGVjdXRvcnEDVQdkZWZhdWx0cQRVDW1heF9pbnN0YW5jZXNxBUsDVQRmdW5jcQZVD19fbWFpbl9fOm15X2pvYnEHVQJpZHEIVSA1NWNhNTRlZTRiYjc0NGY4YTVhYjA4Y2M0MzE5YmMyNHEJVQ1uZXh0X3J1bl90aW1lcQpjZGF0ZXRpbWUKZGF0ZXRpbWUKcQtVCgffBgsSBzoMKUhjcHl0egpfcApxDChVDUFzaWEvU2hhbmdoYWlxDU2AcEsAVQNDU1RxDnRScQ+GUnEQVQRuYW1lcRFVBm15X2pvYnESVRJtaXNmaXJlX2dyYWNlX3RpbWVxE0sBVQd0cmlnZ2VycRRjYXBzY2hlZHVsZXIudHJpZ2dlcnMuaW50ZXJ2YWwKSW50ZXJ2YWxUcmlnZ2VyCnEVKYFxFn1xF1UPaW50ZXJ2YWxfbGVuZ3RocRhHQBQAAAAAAABzfXEZKFUIdGltZXpvbmVxGmgMKGgNTehxSwBVA0xNVHEbdFJxHFUIaW50ZXJ2YWxxHWNkYXRldGltZQp0aW1lZGVsdGEKcR5LAEsFSwCHUnEfVQpzdGFydF9kYXRlcSBoC1UKB98GCxIHIQwpSGgPhlJxIVUIZW5kX2RhdGVxIk51hmJVCGNvYWxlc2NlcSOJVQd2ZXJzaW9ucSRLAVUGa3dhcmdzcSV9cSZ1Lg==") }<span id="mce_marker" data-mce-type="bookmark"></span><span id="__caret">_</span> { "_id" : "55ca54ee4bb744f8a5ab08cc4319bc24", "next_run_time" : 1434017278.797, "job_state" : new BinData(0, "gAJ9cQEoVQRhcmdzcQIpVQhleGVjdXRvcnEDVQdkZWZhdWx0cQRVDW1heF9pbnN0YW5jZXNxBUsDVQRmdW5jcQZVD19fbWFpbl9fOm15X2pvYnEHVQJpZHEIVSA1NWNhNTRlZTRiYjc0NGY4YTVhYjA4Y2M0MzE5YmMyNHEJVQ1uZXh0X3J1bl90aW1lcQpjZGF0ZXRpbWUKZGF0ZXRpbWUKcQtVCgffBgsSBzoMKUhjcHl0egpfcApxDChVDUFzaWEvU2hhbmdoYWlxDU2AcEsAVQNDU1RxDnRScQ+GUnEQVQRuYW1lcRFVBm15X2pvYnESVRJtaXNmaXJlX2dyYWNlX3RpbWVxE0sBVQd0cmlnZ2VycRRjYXBzY2hlZHVsZXIudHJpZ2dlcnMuaW50ZXJ2YWwKSW50ZXJ2YWxUcmlnZ2VyCnEVKYFxFn1xF1UPaW50ZXJ2YWxfbGVuZ3RocRhHQBQAAAAAAABzfXEZKFUIdGltZXpvbmVxGmgMKGgNTehxSwBVA0xNVHEbdFJxHFUIaW50ZXJ2YWxxHWNkYXRldGltZQp0aW1lZGVsdGEKcR5LAEsFSwCHUnEfVQpzdGFydF9kYXRlcSBoC1UKB98GCxIHIQwpSGgPhlJxIVUIZW5kX2RhdGVxIk51hmJVCGNvYWxlc2NlcSOJVQd2ZXJzaW9ucSRLAVUGa3dhcmdzcSV9cSZ1Lg==") }
上面是通过add_job()来添加作业,另外还有一种方式是通过scheduled_job()修饰器来修饰函数。
@sched.scheduled_job('cron', id='my_job_id', day='last sun') def some_decorated_task(): print("I am printed at 00:00:00 on the last Sunday of every month!") 1 @sched.scheduled_job('cron', id='my_job_id', day='last sun') 2 3 def some_decorated_task(): 4 print("I am printed at 00:00:00 on the last Sunday of every month!")
暂停作业: – apscheduler.job.Job.pause() – apscheduler.schedulers.base.BaseScheduler.pause_job() 恢复作业: – apscheduler.job.Job.resume() – apscheduler.schedulers.base.BaseScheduler.resume_job()
获得调度作业的列表,可以使用get_jobs()来完成,它会返回所有的job实例。或者使用print_jobs()来输出所有格式化的作业列表。
默认情况下调度器会等待所有正在运行的作业完成后,关闭所有的调度器和作业存储。如果你不想等待,可以将wait选项设置为False。
scheduler.shutdown() scheduler.shutdown(wait=False) 1 scheduler.shutdown() 2 scheduler.shutdown(wait=False)
add_job的第二个参数是trigger,它管理着作业的调度方式。它可以为date, interval或者cron。对于不同的trigger,对应的参数也相同。
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) 和Linux的Crontab一样,它的值格式为:
ExpressionFieldDescription*anyFire on every value*/aanyFire every a values, starting from the minimuma-banyFire on any value within the a-b range (a must be smaller than b)a-b/canyFire every c values within the a-b rangexth ydayFire on the x -th occurrence of weekday y within the monthlast xdayFire on the last occurrence of weekday x within the monthlastdayFire on the last day within the monthx,y,zanyFire on any matching expression; 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 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') 1 # Schedules job_function to be run on the third Friday 2 # of June, July, August, November and December at 00:00, 01:00, 02:00 and 03:00 3 sched.add_job(job_function, 'cron', month='6-8,11-12', day='3rd fri', hour='0-3') 4 # Runs from Monday to Friday at 5:30 (am) until 2014-05-30 00:00:00 5 sched.add_job(job_function, 'cron', day_of_week='mon-fri', hour=5, minute=30, end_date='2014-05-30')
它的参数如下: 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 例子:
# Schedule job_function to be called every two hours sched.add_job(job_function, 'interval', hours=2) 1 # Schedule job_function to be called every two hours 2 sched.add_job(job_function, 'interval', hours=2)
最基本的一种调度,作业只会执行一次。它的参数如下: 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 例子:
# 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']) 1 # The job will be executed on November 6th, 2009 2 sched.add_job(my_job, 'date', run_date=date(2009, 11, 6), args=['text']) 3 # The job will be executed on November 6th, 2009 at 16:30:05 4 sched.add_job(my_job, 'date', run_date=datetime(2009, 11, 6, 16, 30, 5), args=['text'])原文地址:http://debugo.com/apscheduler/?utm_source=tuicool&utm_medium=referral