Home > Software engineering >  Better way to execute code at a specific time?
Better way to execute code at a specific time?

Time:12-13

I need to execute code at exact time, for example 10:00:00.000.

while True:
    now = datetime.utcnow()

    if now.hour == 10 and now.minute == 0 and now.second == 0:
        #execute code here
    time.sleep(1)

So far it seems to work but if I launch the code for example one hour before launch I feel like there is a lag in the execution?

Is this the best to achieve what I want?

CodePudding user response:

Using datetime and threading.Timer:

from datetime import datetime, time
from threading import Timer


def do_the_thing():
    print("execute code here")


Timer(
    (datetime.combine(
        datetime.today(), time(10, 0, 0)
    ) - datetime.now()).total_seconds(),
    do_the_thing
).start()

Since Timer runs in a background thread, your script can go on to do other things immediately, and do_the_thing will get called as soon as the timer is up.

CodePudding user response:

Simply sleep for the total amount of time wanted:

target_date = datetime(day=12, month=12, year=2021, hour=10)
time.sleep((target_date - datetime.now()).total_seconds())
  • Related