【问题标题】:Can't get code to execute at certain timeCan\'t get code to execute at certain time
【发布时间】:2022-12-01 21:44:10
【问题描述】:
I am trying to get some code to execute at a certain time but I can't figure out what the problem is here. Please help?
import datetime
dt=datetime
set_time=dt.time(12,53)
timenow=dt.datetime.now()
time=False
while not time:
if timenow==set_time:
print("yeeehaaa")
time=True
break
else:
print("naaaaa")
【问题讨论】:
标签:
python
jupyter-notebook
【解决方案1】:
FIrs of all you have to upfdate the time inside the loop or it will always be comparing the same timenow to set_time, then convert all to just an hour/minut string and compare
import datetime
dt=datetime
set_time=str(dt.time(14,19))[0:5]
timenow=dt.datetime.now().time()
time=False
while not time:
timenow=str(dt.datetime.now().time())[0:5]
# print(timenow)
if timenow==set_time:
print("yeeehaaa")
time=True
break
else:
print("naaaaa")
【解决方案2】:
Changing your code to something like this should solve your issue:
import datetime.datetime as dt
set_time=dt.time(12,53)
# the loop waits for the time condition to be met.
# we use the lower than condition in order not to miss the time
# by a few fraction of second.
while (dt.now() < set_time):
time.sleep(0.1) # 100ms delay
# reaching there implies the time condition is met!
print("it is time!")
However there is a much simpler alternative which would consists in get the time delta between the current time and the target time in order to make one single wait with time.sleep(time_delta_s).
【解决方案3】:
As an alternative, have you considered using cron to schedule it?
53 12 * * * /path/to/python /path/to/script.py 2>&1