2

I'd like to schedule a repeated timed event in python like this: "at time X launch function Y (in a separate thread) and repeat every hour"

"X" is fixed timestamp

The code should be cross-platform, so i'd like to avoid using an external program like "cron" to do this.

code extract:

    import threading
    threading.Timer(10*60, mail.check_mail).start()
    #... SET UP TIMED EVENTS HERE
    while(1):
        print("please enter command")
        try:
            command = raw_input()
        except:
            continue
        handle_command(command) 
2
  • 2
    You need to provide more details about your application. Does it use an event loop, etc. Commented May 22, 2012 at 10:49
  • 1
    Why don't use cron? On windows people can use the task scheduler. Commented May 22, 2012 at 10:53

1 Answer 1

2

Create a dateutil.rrule, rr for your schedule and then use a loop like this in your thread:

for ts in rr:
    now = datetime.now()
    if ts < now:
        time.sleep((now - ts).total_seconds())
    # do stuff

Or a better solution that will account for clock changes:

ts = next(rr)
while True:
    now = datetime.now()
    if ts < now:
        time.sleep((now - ts).total_seconds() / 2)
        continue
    # do stuff
    ts = next(rr)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.