Can't get code to execute at certain time

Question:

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")
Asked By: Sam Bridge

||

Answers:

As an alternative, have you considered using cron to schedule it?

53 12 * * * /path/to/python /path/to/script.py 2>&1

Answered By: avocado-eater

First of all you have to update the time inside the loop or it will always be comparing the same timenow to set_time, then convert all to just an hour/minute 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")
Answered By: Indiano

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).

Answered By: Jib
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.