6

I am working on a period task with Python apscheduler, I want the code execute on 9:00, 11:00, 16:00, 17:00 every day and here is an example code for the job:

#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()

It works, but repeat four times code seems silly, so my problem is how to make the code short to set the function run at 9:00, 11:00, 16:00, 17:00 every day?

lqhcpsgbl
  • 3,694
  • 3
  • 21
  • 30

2 Answers2

21

Why would you want to schedule the job four times separately when the documentation gives clear examples of how to do it properly?

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

See this and this.

Alex Grönholm
  • 5,563
  • 29
  • 32
-1

Something like this?

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

or with multiple methods:

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)
user2358582
  • 372
  • 2
  • 10