rSimple python schedule two timed events
我在使用python调度模块的以下场景中遇到了问题。实际上,我想在时间A运行一个登录事件,然后在时间B运行该操作。
代码不会按照预期的行为描述运行,这是我需要帮助的地方。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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() |
编辑我已经将代码修改为以下代码,但是在如何最好地实现这种行为方面,它仍然是不正确的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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() |
号
以下代码尚未测试,但应该有效。我已经将您的原始代码放入注释中,这样您就可以看到哪里出错了。您可能需要参考文档:https://docs.python.org/2/library/sched.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import sched, time 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) #The first argument of sched.scheduler should be a function that return a number. scheduler = sched.scheduler(time.time, 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用于相对延迟。要使用的正确功能是scheduler.enterabs。您需要一个函数来将datetime转换为posix时间戳。在python 2.x中,由于时区问题,这可能很棘手。请参阅以下问题:将datetime转换为unix时间戳,然后将其转换回python此外,函数接受4个参数。
1 2 3 4 5 6 | #scheduler.enter(log, login_event, ('Login')) #scheduler.enter(action, login_event, ('Action')) scheduler.enterabs(timestamp(log), 0, login_event, ('Login')) scheduler.enterabs(timestamp(action), 0, action_event, ('Action')) scheduler.run() |
号
网址:https://github.com/dbader/schedule
通过遵循上面链接的模式,我能够使用稍微不同的计划模块创建所需的行为。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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) |