rSimple python 安排两个定时事件

rSimple python schedule two timed events

我在使用 python 计划模块时遇到以下情况。本质上,我想 运行 时间 A 的登录事件,然后 运行 时间 B 的动作。

该代码没有 运行 预期的行为描述,这是我需要帮助的地方。

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()

编辑 我已将代码更改为以下内容,但就如何最好地实现此行为而言,它似乎仍然不正确。

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

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 您将需要一个将日期时间转换为 POSIX 时间戳的函数。 由于时区问题,这在 python 2.x 中可能会很棘手。 参考这个问题:Convert datetime to Unix timestamp and convert it back in python 此外,该函数有 4 个参数。

#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

按照上面链接的模式,我能够使用稍微不同的计划模块创建所需的行为

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)