# Opinions/Improvements on a run periodically/timer function in Python 2.7

I'm looking for some opinions on this bit of code that I wrote and if there are any ways it can be improved.

The scripts aim is to run the function runme() every 60 seconds with a random interval anywhere between -20 seconds to +40 seconds so it could run randomly anywhere between 40 seconds and 100 seconds.

import sched, time
import random

s = sched.scheduler(time.time, time.sleep)

def periodically(runtime, intsmall, intlarge, function):
runtime += random.randrange(intsmall, intlarge)
s.enter(runtime, 1, function, ())
s.run()

def runme():
print "hi"

while True:
periodically(60, -20, +40, runme)


You can achieve the same by just sleeping for runtime seconds and calling runme() afterwards (you have to sleep before, since the scheduler delays the action for runtime seconds).
Also note that random.randrange(intsmall, intlarge) will return a value between intsmall and intlarge - 1, so your random time will be between 40 seconds and 99 seconds.
• Hi, Thanks for your reply. I don't quite understand are you saying that s.run and s.enter are the wrong way round? I want to avoid: def periodically(runtime, intsmall, intlarge): runtime += random.randrange(intsmall, intlarge) sleep(runtime) runme() – Hyflex Jun 22 '13 at 21:06
• You're welcome. I'm not saying that s.run() and s.enter() are the wrong way round - they are fine as written. But if you replace them with sleep() and runme(), that sequence should be changed. The scheduler delays first and then runs, so you need the sleep before the run, if not using the scheduler but just sleeping and running. – user2512319 Jun 22 '13 at 22:06