Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule an event in python without multithreading?

Tags:

python

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.

like image 857
relima Avatar asked Oct 20 '10 14:10

relima


4 Answers

Maybe sched?

like image 178
eumiro Avatar answered Oct 18 '22 22:10

eumiro


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.

like image 23
Noufal Ibrahim Avatar answered Oct 18 '22 21:10

Noufal Ibrahim


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
like image 2
inspectorG4dget Avatar answered Oct 18 '22 23:10

inspectorG4dget


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.

like image 2
hughdbrown Avatar answered Oct 18 '22 23:10

hughdbrown