tags:

views:

92

answers:

3

Is there an easy way to get a python code segment to run every 5 minutes?

I know I could do it using time.sleep() but was there any other way?

For example I want to run this every 5 minutes:

x = 0
def run_5():
    print "5 minutes later"
    global x += 5
    print x, "minutes since start"

That's only a fake example but the idea is there.

Any ideas?

I am on linux and would happily use cron but was just wondering if there was a python alternative?

+1  A: 

you can do it with the threading module

>>> import threading
>>> END = False
>>> def run(x=0):
...     x += 5
...     print x
...     if not END:
...         threading.Timer(1.0, run, [x]).start()
... 
>>> threading.Timer(1.0, run, [x]).start()
>>> 5
10
15
20
25
30
35
40

Then when you want it to stop, set END = True.

aaronasterling
+2  A: 

You might want to have a look at cron if you are running a *nix type OS. You could easily have it run you program every 5 minutes

http://www.unixgeeks.org/security/newbie/unix/cron-1.html

https://help.ubuntu.com/community/CronHowto

Jonno_FTW
I am on linux and would happily use cron but was just wondering if there was a python alternative?
Fergus Barker
By using cron, each run of your program will be independent. If it crashes or fails on one pass, cron will still execute it again in five minutes. You could mimic that behavior in python, but it would require some thought, especially if you wanted to receive the output of a failed run.
AndrewF
A: 

If you are on a windows platform, you could use a scheduled task.

Otherwise, use cron, wonderful, wonderful cron.

JoshD