2
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

I don't think you do need the scheduler for that, at least not for how you use it. Your loop schedules 1 event and just afterwards waits until it's finished, since run() waits until the scheduled event(s) are completed.

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.

\$\endgroup\$
  • \$\begingroup\$ 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() \$\endgroup\$ – Hyflex Jun 22 '13 at 21:06
  • \$\begingroup\$ 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. \$\endgroup\$ – user2512319 Jun 22 '13 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.