Is it possible to schedule an event in python without multithreading? I am trying to obtain something like scheduling a function to execute every x seconds.
5 Answers
Maybe sched?
1 Comment
You could use a combination of signal.alarm and a signal handler for SIGALRM like so to repeat the function every 5 seconds.
import signal
def handler(sig, frame):
print ("I am done this time")
signal.alarm(5) #Schedule this to happen again.
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
The other option is to use the sched module that comes along with Python but I don't know whether it uses threads or not.
1 Comment
sched runs a classic "run loop", which means you provide it with a bunch of functions that are intended to be called at scheduled times, and then turn control over to sched.run() to handle the scheduling and callbacks. It doesn't seem to use threads, or in fact be thread-safe. It also doesn't seem to handle any events other than timeouts.Sched is probably the way to go for this, as @eumiro points out. However, if you don't want to do that, then you could do this:
import time
while 1:
#call your event
time.sleep(x) #wait for x many seconds before calling the script again
1 Comment
x seconds completely not allowing it to do anything.Without threading it seldom makes sense to periodically call a function. Because your main thread is blocked by waiting - it simply does nothing. However if you really want to do so:
import time
for x in range(3):
print('Loop start')
time.sleep(2)
print('Calling some function...')
I this what you really want?
1 Comment
You could use celery:
Celery is an open source asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well.
The execution units, called tasks, are executed concurrently on one or more worker nodes. Tasks can execute asynchronously (in the background) or synchronously (wait until ready).
and a code example:
You probably want to see some code by now, so here’s an example task adding two numbers:
from celery.decorators import task
@task
def add(x, y):
return x + y
You can execute the task in the background, or wait for it to finish:
>>> result = add.delay(4, 4)
>>> result.wait() # wait for and return the result 8
This is of more general use than the problem you describe requires, though.
1 Comment
@task part was incorrectly formatted.