from datetime import datetime import threading mydate = datetime.now() #сегодня time_start=mydate.replace(day=mydate.day+1, hour=3, minute=4)#время запуска def starter():#произвольная функция print('hello world') delta_time=time_start-mydate#разница между запуском и сейчас reload=delta_time.seconds+1 #эта же разница в секундах s = threading.Timer(reload, starter)#запуск функции starter, через заданное количество секунд s.start() 

My question is: how to loop the execution of a function, so that it runs (without restarting the script) once a day according to the timer?

  • Either describe explicitly what you see the problem with your code: what was expected to get what was happening instead. Or change the question title to: "how to perform the function once a day at a specified time without restarting the script." Explicitly indicate the reasons why "without restarting". Related question: Before finishing work at 6:00 pm write print ("END") - jfs

2 answers 2

To execute code every day at a specified time, it is easier and more reliable to use operating system tools such as cron or Windows task scheduler to run a script that performs the action and exits. Otherwise, you have to independently solve such problems as:

  • who will restart the script if it dies for any reason (memory is over, unexpected error) - you can run the script as a service (daemon) from under systemd, supervisord, etc
  • who will restart the script if it hangs (the process is alive, but does not perform any actions) - a service (watchdog) may be required, which listens to the periodic signals (heartbeat) and restarts the script if it stopped sending them. In turn, someone must ensure that the watchdog service itself is operational, and so on.

If you forget about these problems, you can run the function at a given time using sched.scheduler() :

 #!/usr/bin/env python3 import datetime as DT import sched import time DAY = DT.timedelta(1) def some_func(dt): print(dt) # do something dt += DAY s.enterabs(dt.timestamp(), 0, some_func, [dt]) # schedule the next time s = sched.scheduler(time.time) dt = DT.datetime.combine(DT.datetime.today(), DT.time(10, 0)) # today 10:00 s.enterabs(dt.timestamp(), 0, some_func, [dt]) s.run() 
     from threading import Timer def starter(): print('hello world') Timer(1, starter).start() starter()