Search code examples
pythonschedulepython-datetime

rSimple python schedule two timed events


I am having trouble with the following scenario using python schedule module. Essentially I want to run a login event at time A, and then run the action at time B.

The code does not run as the intended behaviour describes and this is where I need help.

import sched
import datetime

today = datetime.datetime.today()
log = today.replace(hour=11, minute=59, second = 0)
action= today.replace(hour=12, minute=0, second = 0)

scheduler = sched.scheduler(datetime.datetime.today(), time.sleep)

def login_event(name):
    print 'EVENT:', datetime.datetime.today(), name

def action_event(name):
    print 'EVENT:' datetime.datetime.today(),name

print 'START:', time.time()
scheduler.enter(log, login_event, ('Login'))
scheduler.enter(action, login_event, ('Action'))

scheduler.run()

EDIT I have altered the code to the following but it still doesn't seem right in terms of how best to implement this behaviour.

import sched
import datetime
from datetime import timedelta
import datetime
import time

today = datetime.datetime.today()
log = datetime.datetime.now() + timedelta(minutes=1)# today.replace(hour=12, minute=46, second = 0)
action= log + timedelta(minutes=2)


scheduler = sched.scheduler(time.time, time.sleep)
print datetime.datetime.now

def login_event(name):
    print 'Login:', datetime.datetime.now(), name

def action_event(name):
    print 'Action:', datetime.datetime.now(), name

print 'Start:', datetime.datetime.now()

scheduler.enter(1, 1, login_event, ('first',))
scheduler.enter(60, 1, action_event, ('second',))

scheduler.run()

Solution

  • https://github.com/dbader/schedule

    By following the pattern linked above I was able to create the desired behaviour using a slightly different schedule module

    import schedule
    import time
    
    def job():
        print("I'm working on job one...")
    
    def job2():
        print("I'm working on job two..")
    
    schedule.every().day.at("10:30").do(job)
    schedule.every().day.at("10:35").do(job2)
    
    
    while True:
        schedule.run_pending()
        time.sleep(1)