如何在每天 9、11、14、17、18 时钟设置 Python apscheduler 运行 作业

How to set Python apscheduler run job at 9,11,14,17,18 clock everyday

我正在使用 Python apscheduler 执行周期任务,我希望代码在 9:00、11:00、16:00、17:00 上执行天,这里是工作的示例代码:

#coding=utf-8
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
logging.basicConfig()
from time import ctime

sched = BlockingScheduler()

@sched.scheduled_job('cron', hour=16)
def timed_job_one():
    print "16"
    print ctime()

@sched.scheduled_job('cron', hour=17)
def timed_job_one():
    print "17"
    print ctime()

@sched.scheduled_job('cron', hour=9)
def timed_job_two():
    print ctime()
    print '9'

@sched.scheduled_job('cron', hour=11)
def timed_job_two():
    print ctime()
    print '11'

sched.start()

有效,但重复四次代码似乎很愚蠢,所以我的问题是如何缩短代码以将函数 运行 设置为 9:00、11:00、16:00, 17:00 每天?

是这样的吗?

for h in [9,11,16,17]:
    @sched.scheduled_job('cron', hour=h)
    def timed_job_one():
        print h
        print ctime()

或使用多种方法:

items = [(16,timed_job_one),(17,timed_job_one),(9,timed_job_two),(11,timed_job_two)]
for h,method in items:
 @sched.scheduled_job('cron', hour=h)
    def job():
        method(h)

当文档清楚地说明如何正确执行时,您为什么要分别安排四次作业?

@sched.scheduled_job('cron', hour='9,11,16,17')
def timed_job():
    print ctime()

this and this