提问人:JohnnyPicnic 提问时间:2/1/2023 最后编辑:WoodfordJohnnyPicnic 更新时间:2/1/2023 访问量:65
每天 14:00 运行一次任务,如果睡觉,请尽快运行任务
Run task once at 14:00 everyday or as soon as possible if sleeping
问:
我将如何仅使用日期和时间运行任务,以便它只运行一次,即使确切时间不匹配,因为程序一直在休眠,它也会运行? 我可以做一个 if 小时、if 分钟和 if 秒,但我在循环之间睡觉,所以它可能不会看到那个确切的时间。
if (rtc.getHour() == 14):
if (rtc.getMinutes() == 00):
if (rtc.getSeconds() == 00):
答:
0赞
111
2/1/2023
#1
import schedule
import time
def your_task():
# Your task
print("Task executed")
schedule.every().day.at("14:00:00").do(your_task)
while True:
schedule.run_pending()
time.sleep(1)
这将在每天 14:00:00 运行您的任务,无论程序是否处于睡眠状态。
编辑:
import time
import json
def your_task():
# Your task
print("Task executed")
def run_pending_tasks():
current_time = time.localtime()
global last_execution_time
last_execution_time_converted = time.strptime(last_execution_time, '%Y-%m-%d %H:%M:%S')
current_date = time.strftime("%Y-%m-%d", current_time)
if current_date in execution_data:
if execution_data[current_date] == 1:
return
execution_data[current_date] += 1
else:
execution_data[current_date] = 1
if (current_time.tm_hour >= 14 and current_time.tm_min >= 0 and current_time.tm_sec >= 0) and (time.mktime(current_time) - time.mktime(last_execution_time_converted)) >= 86400: # 86400 seconds in a day
your_task()
last_execution_time = time.strftime('%Y-%m-%d %H:%M:%S', current_time)
with open('execution_data.json', 'w') as file:
json.dump(execution_data, file)
last_execution_time = '2000-01-01 00:00:00'
try:
with open('execution_data.json', 'r') as file:
execution_data = json.load(file)
except FileNotFoundError:
execution_data = {}
while True:
run_pending_tasks()
time.sleep(300)
评论
0赞
JohnnyPicnic
2/1/2023
我的程序一次休眠 5 分钟,这还能用吗?如果醒来时时间是 14:00:05 怎么办?
0赞
111
2/1/2023
我添加了新版本的代码,新代码将适用于您的方案
评论
has_it_ran
False
if rtc.getHour() >= 14 and not has_it_ran
has_it_ran