Python - 在给定时间启动函数

时间:2012-07-17 13:49:25

标签: python time scheduler

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

例如:

run_it_at(func, '2012-07-17 15:50:00')

它将在2012-07-17 15:50:00运行函数func

我尝试了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, ())

我该怎么办?

9 个答案:

答案 0 :(得分:20)

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

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

from datetime import datetime
now = datetime.now()

然后使用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()

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

threading.Timer(delay, self.update).start()

答案 1 :(得分:17)

查看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'])

答案 2 :(得分:10)

以下是使用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()

答案 3 :(得分:8)

可能值得安装这个库: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)

答案 4 :(得分:3)

我遇到了同样的问题:sched.enterabs无法识别sched.run注册的绝对时间事件。如果我计算sched.enterdelay为我工作,但由于我希望工作在特定时区的特定时间运行,因此很难使用。

在我的情况下,我发现问题是timefunc初始化程序中的默认sched.scheduler不是time.time(如example中所示),而是time.monotonictime.monotonic对“绝对”时间表没有任何意义,因为从docs开始,“返回值的参考点未定义,因此只有连续调用结果之间的差异才有效。“

我的解决方案是将调度程序初始化为

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

目前还不清楚你的time_module.time实际上是time.time还是time.monotonic,但是当我正确初始化它时它工作正常。

答案 5 :(得分:3)

我已经确认了开篇文章中的代码,只是缺少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
>>>

答案 6 :(得分:0)

dateSTR = datetime.datetime.now().strftime("%H:%M:%S" )
if dateSTR == ("20:32:10"):
   #do function
    print(dateSTR)
else:
    # do something useful till this time
    time.sleep(1)
    pass

只需查找时间/日期事件触发器: 只要日期"字符串"与更新的" time"相关联string,它作为一个简单的TOD函数。您可以将字符串扩展到日期和时间。

是否按字典排序或按时间顺序比较, 只要字符串代表一个时间点,字符串也会。

有人提供了这个链接:

String Comparison Technique Used by Python

答案 7 :(得分:0)

很难获得这些答案以按我的需要去工作,

但是我成功了,它的精确到.01秒

from apscheduler.schedulers.background import BackgroundScheduler
    
sched = BackgroundScheduler()
sched.start()

def myjob():
    print('job 1 done at: ' + str(dt.now())[:-3])

dt = datetime.datetime
Future = dt.now() + datetime.timedelta(milliseconds=2000)
job = sched.add_job(myjob, 'date', run_date=Future)

使用以下代码测试了计时的准确性: 起初我做了2秒和5秒的延迟,但是想用更精确的测量来测试它,所以我以2.55秒的延迟和5.55秒的延迟再次尝试

dt = datetime.datetime
Future = dt.now() + datetime.timedelta(milliseconds=2550)
Future2 = dt.now() + datetime.timedelta(milliseconds=5550)

def myjob1():
    print('job 1 done at: ' + str(dt.now())[:-3])
def myjob2():
    print('job 2 done at: ' + str(dt.now())[:-3])

print(' current time: ' + str(dt.now())[:-3])
print('  do job 1 at: ' + str(Future)[:-3] + ''' 
  do job 2 at: ''' + str(Future2)[:-3])
job = sched.add_job(myjob1, 'date', run_date=Future)
job2 = sched.add_job(myjob2, 'date', run_date=Future2)

并获得以下结果:

 current time: 2020-12-10 19:50:44.632
  do job 1 at: 2020-12-10 19:50:47.182 
  do job 2 at: 2020-12-10 19:50:50.182
job 1 done at: 2020-12-10 19:50:47.184
job 2 done at: 2020-12-10 19:50:50.183

通过1次测试精确到0.002秒

但是我确实进行了很多测试,准确性范围从.002到.011

从不超过2.55或5.55秒的延迟

答案 8 :(得分:-1)

#everytime you print action_now it will check your current time and tell you should be done

import datetime  
current_time = datetime.datetime.now()  
current_time.hour  

schedule = {
    '8':'prep',
    '9':'Note review',
    '10':'code',
    '11':'15 min teabreak ',
    '12':'code',
    '13':'Lunch Break',
    '14':'Test',
    '15':'Talk',
    '16':'30 min for code ',
    '17':'Free',
    '18':'Help ',
    '19':'watever',
    '20':'watever',
    '21':'watever',
    '22':'watever'
}

action_now = schedule[str(current_time.hour)]