Python安排每个工作日开始并每小时运行一次的作业

时间:2017-11-03 00:37:15

标签: python-3.x schedule

我目前的示例代码定义为:

import schedule
import time

def job(t):
    print ("I'm working...", t)
    return

schedule.every().day.at("01:00").do(job,'It is 01:00')

while True:
    schedule.run_pending()
    time.sleep(60) # wait one minute

我希望在工作日的每个小时从早上9点到下午4点运行代码。即每周一至周五,我希望在上午9点,上午10点,下午3点,下午4点运行代码。

阅读schedule的文档似乎我可以单独MondayFriday运行代码,但不仅仅是在两个指定时间之间的工作日。

此外,以下time.sleep(60)不应该让代码永久运行吗?

3 个答案:

答案 0 :(得分:1)

#standardSQL
SELECT 
  TIME(TIMESTAMP_ADD(TIMESTAMP(CURRENT_DATE()), INTERVAL timestart MINUTE)) AS tbegin
FROM `project.dataset.table`  

答案 1 :(得分:1)

它对我有用的唯一方法是:

import schedule
import datetime
import time

nowtime = str(datetime.datetime.now())

def job(t):
    print("I'm working...", str(datetime.datetime.now()), t)

for i in ["06:00", "09:00", "12:00", "15:00", "18:00"]:
    schedule.every().monday.at(i).do(job, i)
    schedule.every().tuesday.at(i).do(job, i)
    schedule.every().wednesday.at(i).do(job, i)
    schedule.every().thursday.at(i).do(job, i)
    schedule.every().friday.at(i).do(job, i)

while True:
    schedule.run_pending()
    time.sleep(30)

答案 2 :(得分:1)

您可以使用库APScheduler。例如:

from apscheduler.schedulers.blocking import BlockingScheduler

def job_function():
    print("Hello World")

sched = BlockingScheduler()

# 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)
sched.start()