How to Repeatedly Execute a Function Every X Seconds

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

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

Call function every x seconds (Python)

Just remember when the next iteration is supposed to happen, roughly like this (not fully working code, I'm sure you can figure it out from here):

import time
nexttime = time.time()
while True:
func() # take t sec
nexttime += 10
sleeptime = nexttime - time.time()
if sleeptime > 0:
time.sleep(sleeptime)

flutter run function every x amount of seconds

build() can and usually will be called more than once and every time a new Timer.periodic is created.

You need to move that code out of build() like

Timer? timer;

@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 15), (Timer t) => checkForNewSharedLists());
}

@override
void dispose() {
timer?.cancel();
super.dispose();
}

Even better would be to move out such code from widgets entirely in an API layer or similar and use a StreamBuilder to have the view updated in case of updated data.

Call a function every X seconds

const reloadInterval = 60;

timer(0, reloadInterval).pipe(
mergeMap(_ => this.myService.myHttpCall())
).subscribe()

That's to answer your question. But honnestly I do not think that's a good idea to do that from a component and you should rather do that directly from your service.

Also, if you're looking for a more advanced answer you can take a look here.

Way to repeatedly execute a function without extra modules every x seconds?

If you have turtle available, then you have tkinter available as turtle.TK. You can then use root.after(1200, function. args) to execute function(*args) every 1.2 seconds. Searching SO for [tkinter] root.after will give numerous questions with helpful examples. However, once you do that, you must make everything event driven and event handlers should not take so long as to block the event loop.

EDIT: turtle wraps tkinter.after as turtle.ontimer(function, milleseconds). The function cannot take arguments. If this is a 'homework' problem of some sort, this may be the intended solution. There is an example here.



Related Topics



Leave a reply



Submit