Executing Periodic Actions

Executing periodic actions

At the end of foo(), create a Timer which calls foo() itself after 10 seconds.

Because, Timer create a new thread to call foo().

You can do other stuff without being blocked.

import time, threading
def foo():
print(time.ctime())
threading.Timer(10, foo).start()

foo()

#output:
#Thu Dec 22 14:46:08 2011
#Thu Dec 22 14:46:18 2011
#Thu Dec 22 14:46:28 2011
#Thu Dec 22 14:46:38 2011

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

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.

Python Celery does not execute periodic tasks at all

app.conf.beat_schedule={
"task":"your task",
"schedule":"your schedule"
}

Did you add the above snippet in celery.py file?

https://docs.celeryproject.org/en/stable/userguide/periodic-tasks.html



Related Topics



Leave a reply



Submit