Python 在${someone}上调度代码执行的干净方法,而无需重新尝试,如何?
我对编写python代码和在特定时间内只执行一次代码很陌生。有点像轮询时间 这里我想在凌晨00:30执行Python 在${someone}上调度代码执行的干净方法,而无需重新尝试,如何?,python,Python,我对编写python代码和在特定时间内只执行一次代码很陌生。有点像轮询时间 这里我想在凌晨00:30执行 while True: now = datetime.datetime.now() if now.hour == 0 and now.minute == 30: print "Hit" # will use this line to call another function or code time.sleep(100) t
while True:
now = datetime.datetime.now()
if now.hour == 0 and now.minute == 30:
print "Hit" # will use this line to call another function or code
time.sleep(100)
time.sleep(5) # to avoid hogging up cpu
使用无限循环和睡眠(100),100秒足以执行一次打印
- python中有没有更健壮的方法来实现这一点
和
之间做任何其他工作,您只需计算两点之间的秒数,然后在整个持续时间内睡眠
from datetime import datetime as dt, time as t
from time import sleep
我们必须意识到,如果时间已经过去,那么使用dt.now()
并以上面的方式明确设置时间可能会导致secs
中出现负数
为了弥补前面提到的不足,我们需要确保我们的计划执行是在未来进行的(如果我们必须等到明天,我们的
目标将有效地增加一天):
在循环中运行它
如果要在循环中运行,只需在每次迭代中将目标增加一天,就不必担心触发相同的工作两次
import datetime as datetime_m
from datetime import datetime as dt, time as t
from time import sleep
def work ():
pass
target = dt.combine (dt.now (), t (hour=0,minute=30,second=0))
if (target < dt.now ()):
target += datetime_m.timedelta (days=1)
while True:
seconds_until_execution = (target - dt.now ()).total_seconds ()
sleep (seconds_until_execution) # wait
work () # execute
target += datetime_m.timedelta (days=1) # queue next
将datetime导入为datetime\m
从datetime导入datetime作为dt,时间作为t
从时间上导入睡眠
定义工作():
通过
目标=dt.combine(dt.now(),t(小时=0,分钟=30,秒=0))
如果(目标
退房
target = dt.combine (dt.now (), t (hour=10,minute=36,second=30))
secs = (target - dt.now ()).total_seconds ()
import datetime as datetime_m
from datetime import datetime as dt, time as t
from time import sleep
...
target = dt.combine (dt.now (), t (hour=0,minute=30,second=0))
if (target < dt.now ()):
target += datetime_m.timedelta(days=1)
...
import datetime as datetime_m
from datetime import datetime as dt, time as t
from time import sleep
def work ():
pass
target = dt.combine (dt.now (), t (hour=0,minute=30,second=0))
if (target < dt.now ()):
target += datetime_m.timedelta (days=1)
while True:
seconds_until_execution = (target - dt.now ()).total_seconds ()
sleep (seconds_until_execution) # wait
work () # execute
target += datetime_m.timedelta (days=1) # queue next