tags:

views:

69

answers:

5

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.

+3  A: 

Maybe sched?

eumiro
This looks like to be exactly what I am looking for, thanks.
relima
If it is exactly what you are looking for, push the I-Love-Your-Answer button.
hughdbrown
+2  A: 

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.

Noufal Ibrahim
+2  A: 

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
inspectorG4dget
Is this what you want? This would block your application for `x` seconds completely not allowing it to do anything.
Noufal Ibrahim
+1  A: 

Hi. 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?

Ondrej Vencovsky
I'm quite sure that this is not what he wanted. :)
Noufal Ibrahim
+2  A: 

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.

hughdbrown
@Noufal Ibrahim: Thanks for the catch. I did not notice that when I cut and pasted the code from the celery site that the `@task` part was incorrectly formatted.
hughdbrown
You're welcome Hugh.
Noufal Ibrahim