eadmaster
eadmaster

Reputation: 1457

how to schedule a timed event in python

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) 

Upvotes: 2

Views: 5029

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318808

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)

Upvotes: 2

Related Questions