每天 14:00 运行一次任务,如果睡觉,请尽快运行任务

Run task once at 14:00 everyday or as soon as possible if sleeping

提问人:JohnnyPicnic 提问时间:2/1/2023 最后编辑:WoodfordJohnnyPicnic 更新时间:2/1/2023 访问量:65

问:

我将如何仅使用日期和时间运行任务,以便它只运行一次,即使确切时间不匹配,因为程序一直在休眠,它也会运行? 我可以做一个 if 小时、if 分钟和 if 秒,但我在循环之间睡觉,所以它可能不会看到那个确切的时间。

if (rtc.getHour() == 14):
    if (rtc.getMinutes() == 00):
        if (rtc.getSeconds() == 00):
蟒蛇 micropython

评论

0赞 saurabheights 2/1/2023
将代码更改为 while True: sleep 30 seconds;然后执行此操作 - 将上次运行时间保存在某个文件中。将此值读取为 last_run_time,如果last_run_time今天 14:00:00 <,并且当前时间为 >= 14:00:00,则运行任务并将当前时间保存到文件中。
0赞 Michael Cao 2/1/2023
添加一个标志并将其设置为等于 initial。然后,如果它当前或超过计划时间并且当天没有运行,则使用 so,然后运行所需的任何任务,然后将标志设置为 True。has_it_ranFalseif rtc.getHour() >= 14 and not has_it_ranhas_it_ran
0赞 saurabheights 2/1/2023
Michael Cao 和我提到的是一样的,但使用 file/db 来节省上次运行时间。重新运行代码/应用程序仍将保留应用状态,并且您不会意外地多次运行某些内容
0赞 JohnnyPicnic 2/1/2023
我认为如果我只存储has_it_ran标志,如果与小时相比,它仍然可以运行。我认为 saurabheights 是我需要存储它运行的时间。
0赞 JohnnyPicnic 2/1/2023
如何在第一次运行时获得最后一次运行?不确定如何获取存储的数字(如果它是比较的一部分)

答:

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
我添加了新版本的代码,新代码将适用于您的方案