在特定时间范围内启动功能

Start a Function at a specific time range

我需要每 5 分钟 运行 一个特定的功能,从周日晚上 11 点开始到周五晚上 11 点。 我该怎么做?我尝试使用“计划”模块,在打印即时时间的一般功能下面

import time
from datetime import datetime

def script_sample():
  now = datetime.now()
  print(now)

schedule.every(5).minutes.sunday.at("23:00").until.friday.at("23:00").do(script_sample)
while True:
  schedule.run_pending()

但我收到以下错误:

AttributeError: 'function' object has no attribute 'friday'

我该怎么做? “安排”是这项任务的正确模块吗?

您不能直接将 until 条件设置为时间表 API 中的星期几和时间,但可以将明确的日期时间、时间或 timedelta 对象设置为 until() 函数中的参数。参见 apidocs

此外,您不能将工作安排在一周中的某一天和每 x 分钟一次。 schedule.every(5).minutes.sunday.at("23:00") 之类的东西是不允许的。

尝试这样的操作,首先找到下周日的日期,然后从中计算下周五的日期。现在您有了开始和结束时间。

接下来调用sleep直到开始时间就可以开始调度job了

import time
from datetime import datetime, timedelta
import schedule

def script_sample():
    now = datetime.now()
    print(now)

now = datetime.now()
# find date of next sunday
d = now
# weekday():  Monday is 0 and Sunday is 6
while d.weekday() != 6:
    d += timedelta(days=1)
d = d.replace(hour=23, minute=00, second=0, microsecond=0)
print("now=", now)
print("next sunday", d) # start date
wait_time = d - now

wait_time_secs = wait_time.total_seconds()
if wait_time_secs > 0:
    print("wait time is ", wait_time)
    print("waiting to start...")
    time.sleep(wait_time_secs)
else:
    print("no need to wait. let's get started')

这部分代码将在周日 23:00 时完成,或者如果它是在 23:00 之后的周日开始的,则在周日晚些时候完成。

下面代码的第 2 部分是确定 until 条件并将作业安排到 运行。接下来找到下周五的日期,这是时间表中的 until 条件。最后将作业安排到每 5 分钟 运行,直到周五 23:00。

# next find date of next Friday (friday=5)
while d.weekday() != 5:
    d += timedelta(days=1)
endtime = d.replace(hour=23, minute=00, second=0, microsecond=0)
print("end time", endtime)

# now schedule a job every 5 mins until the end time
schedule.every(5).minutes.until(endtime).do(script_sample)

while True:
    schedule.run_pending()