Python - 在给定时间启动函数

mic*_*oo8 24 python time scheduler

如何在给定时间在Python中运行函数?

例如:

run_it_at(func, '2012-07-17 15:50:00')
Run Code Online (Sandbox Code Playgroud)

它将func在2012-07-17 15:50:00 运行该功能.

我尝试了sched.scheduler,但它没有启动我的功能.

import time as time_module
scheduler = sched.scheduler(time_module.time, time_module.sleep)
t = time_module.strptime('2012-07-17 15:50:00', '%Y-%m-%d %H:%M:%S')
t = time_module.mktime(t)
scheduler_e = scheduler.enterabs(t, 1, self.update, ())
Run Code Online (Sandbox Code Playgroud)

我能做什么?

Jon*_*nts 21

阅读http://docs.python.org/py3k/library/sched.html上的文档:

从那以后我们需要计算延迟(以秒为单位)......

from datetime import datetime
now = datetime.now()
Run Code Online (Sandbox Code Playgroud)

然后使用datetime.strptime解析'2012-07-17 15:50:00'(我会留下格式字符串给你)

# I'm just creating a datetime in 3 hours... (you'd use output from above)
from datetime import timedelta
run_at = now + timedelta(hours=3)
delay = (run_at - now).total_seconds()
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用delay传递给 threading.Timer实例,例如:

threading.Timer(delay, self.update).start()
Run Code Online (Sandbox Code Playgroud)

  • 如果本地时区的utc偏移在`now`和`run_at`之间变化,例如在DST转换周围,则本地时间的日期时间算术可能会失败.将本地时间转换为UTC或POSIX时间戳以执行计算.请参阅[查找日期时间之间是否已经过了24小时 - Python](http://stackoverflow.com/a/26313848/4279). (3认同)
  • 这个方法有多准确?我正在寻找小于 10 毫秒的错误 (3认同)
  • 您可以直接在`timedelta`上使用`total_seconds`:`datetime.timedelta(hours = 3).total_seconds()` (2认同)

ste*_*bez 18

看一下Advanced Python Scheduler,APScheduler:http://packages.python.org/APScheduler/index.html

他们有一个这个用例的例子:http: //packages.python.org/APScheduler/dateschedule.html

from datetime import date
from apscheduler.scheduler import Scheduler

# Start the scheduler
sched = Scheduler()
sched.start()

# Define the function that is to be executed
def my_job(text):
    print text

# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)

# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])
Run Code Online (Sandbox Code Playgroud)


小智 11

可能值得安装这个库:https://pypi.python.org/pypi/schedule,基本上可以帮助您完成刚刚描述的所有内容.这是一个例子:

import schedule
import time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“schedule”不考虑“job”的持续时间;如果“job”需要 2 分钟,那么“schedule.every().hour.do(job)”实际上每 62 分钟运行一次。IMO APScheduler 是一个更好的软件包。 (2认同)

use*_*278 11

以下是使用Python 2.7对stephenbez对APScheduler 3.5版的回答:

import os, time
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta


def tick(text):
    print(text + '! The time is: %s' % datetime.now())


scheduler = BackgroundScheduler()
dd = datetime.now() + timedelta(seconds=3)
scheduler.add_job(tick, 'date',run_date=dd, args=['TICK'])

dd = datetime.now() + timedelta(seconds=6)
scheduler.add_job(tick, 'date',run_date=dd, kwargs={'text':'TOCK'})

scheduler.start()
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

try:
    # This is here to simulate application activity (which keeps the main thread alive).
    while True:
        time.sleep(2)
except (KeyboardInterrupt, SystemExit):
    # Not strictly necessary if daemonic mode is enabled but should be done if possible
    scheduler.shutdown()
Run Code Online (Sandbox Code Playgroud)


小智 7

我已经确认开头帖子中的代码有效,只是缺少scheduler.run(). 已测试并运行预定的事件。所以这是另一个有效的答案。

>>> import sched
>>> import time as time_module
>>> def myfunc(): print("Working")
...
>>> scheduler = sched.scheduler(time_module.time, time_module.sleep)
>>> t = time_module.strptime('2020-01-11 13:36:00', '%Y-%m-%d %H:%M:%S')
>>> t = time_module.mktime(t)
>>> scheduler_e = scheduler.enterabs(t, 1, myfunc, ())
>>> scheduler.run()
Working
>>>
Run Code Online (Sandbox Code Playgroud)