Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to repeatedly execute a function every x seconds? [closed]

Tags:

python

timer

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?

like image 256
davidmytton Avatar asked Jan 23 '09 21:01

davidmytton


People also ask

How do you call a function repeatedly after a fixed time interval in Python?

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.

How do you repeat a code in Python?

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.


2 Answers

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.

like image 100
nosklo Avatar answered Nov 11 '22 18:11

nosklo


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)) 
like image 28
Dave Rove Avatar answered Nov 11 '22 17:11

Dave Rove