安排代码在以后的某个时间执行 [英] schedule code to execute at some time later

查看:142
本文介绍了安排代码在以后的某个时间执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何安排一些代码在以后的某个特定时间执行?

How can I schedule some code to be executed at a certain time later?

我尝试过:

import time
import datetime

time.sleep(420)
print(datetime.datetime.now())

但是,如果Mac进入睡眠状态,这将不起作用.

But this doesn't work if the Mac goes to sleep.

为了明确起见,我需要一个脚本(嗯,一些python函数,我可以将其放到一个单独的脚本中)在将来的准确时间运行.

To clarify, I need a script (well, some python function, which I could put into a separate script) to run at a precise time in the future.

time.sleep不能满足我的需求,因为如果计算机在time.sleep超时期间进入睡眠状态,则实时延迟将比传递给time.sleep的延迟长得多.例如,我在12:00从time.sleep开始延迟7分钟.然后,我关闭我的Macbook盒盖.在12:07打开它,但是超时尚未结束.实际上,我必须等到大约12:13才能完成超时,尽管起初我希望其余脚本在12:07继续.

time.sleep doesn't meet my needs because if the computer sleeps during time.sleep's timeout then the real-time delay is much longer than the one passed to time.sleep. E.g., I start a 7 minute delay at 12:00 with time.sleep. Then I close my macbook lid. Open it at 12:07, but the timeout hasn't finished yet. In fact, I have to wait until about 12:13 for the timeout to finish, even though originally I wanted the rest of my script to continue at 12:07.

因此,我不需要它在计算机休眠时运行 ,但是,计算机的任何休眠都不会影响计算机运行的时间.

So, I don't need it to run while the computer sleeps, but rather, any sleeping the computer does should not affect the time that it does run.

推荐答案

更新:用户@ I'L'I指出我的代码中有错误.在复制粘贴wait_time变量的过程中,我在timedelta中重写了必要的seconds=,这阻止了循环的退出.现在,此问题已解决.

Update: User @I'L'I pointed out that there was an error in my code. In copy pasting the wait_time variable, I overwrote a necessary seconds= in timedelta which prevented the loop from ever exiting. This is now fixed.

您的代码将等待,直到程序运行了指定的秒数.根据您的问题,您实际上不想要那是正确的吗?实际上,您实际上要等到从开始时间开始经过一定的秒数,然后在经过秒数后的第一个机会继续.

Your code waits until the program has run for a set number of seconds. You don't actually want that, according to your Question, correct? You actually want to wait until a certain number of seconds have passed from your start time, and continue at the first opportunity after they have passed.

执行此操作:

from datetime import datetime
from datetime import timedelta

# Establish the start time as a static variable. Basically lock the start time in.
start_time = datetime.now()

# How long should we wait?
wait_time = 420

# What should I say while I wait?
wait_string = "Zzzzzzzzzzz"

# Loop until at least wait_time seconds have passed
while datetime.now() <= start_time + timedelta(seconds=wait_time):
    print(wait_string, end = "\r"),

print("Done waiting at:", datetime.now())

这篇关于安排代码在以后的某个时间执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆