I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C or setTimeout in JS). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.
In this question about a cron implemented in Python, the solution appears to effectively just sleep() for x seconds. I don't need such advanced functionality so perhaps something like this would work
while True: # Code executed here time.sleep(60)
Are there any foreseeable problems with this code?
start() and stop() are safe to call multiple times even if the timer has already started/stopped. function to be called can have positional and named arguments. You can change interval anytime, it will be effective after next run.
Method 1: Using Time Module We can create a Python script that will be executed at every particular time. We will pass the given interval in the time. sleep() function and make while loop is true. The function will sleep for the given time interval.
If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.
import sched, time s = sched.scheduler(time.time, time.sleep) def do_something(sc): print("Doing stuff...") # do your stuff s.enter(60, 1, do_something, (sc,)) s.enter(60, 1, do_something, (s,)) s.run()
If you're already using an event loop library like asyncio
, trio
, tkinter
, PyQt5
, gobject
, kivy
, and many others - just schedule the task using your existing event loop library's methods, instead.
Lock your time loop to the system clock like this:
import time starttime = time.time() while True: print("tick") time.sleep(60.0 - ((time.time() - starttime) % 60.0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With