Python - Start a Function at Given Time

对着背影说爱祢 提交于 2019-12-17 02:35:10

问题


How can I run a function in Python, at a given time?

For example:

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

and it will run the function func at 2012-07-17 15:50:00.

I tried the sched.scheduler, but it didn't start my function.

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

What can I do?


回答1:


Reading the docs from http://docs.python.org/py3k/library/sched.html:

Going from that we need to work out a delay (in seconds)...

from datetime import datetime
now = datetime.now()

Then use datetime.strptime to parse '2012-07-17 15:50:00' (I'll leave the format string to you)

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

You can then use delay to pass into a threading.Timer instance, eg:

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



回答2:


Take a look at the Advanced Python Scheduler, APScheduler: http://packages.python.org/APScheduler/index.html

They have an example for just this usecase: 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'])



回答3:


Might be worth installing this library: https://pypi.python.org/pypi/schedule, basically helps do everything you just described. Here's an example:

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:


Here's an update to stephenbez' answer for version 3.5 of APScheduler using Python 2.7:

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



回答5:


I ran into the same issue: I could not get absolute time events registered with sched.enterabs to be recognized by sched.run. sched.enter worked for me if I calculated a delay, but is awkward to use since I want jobs to run at specific times of day in particular time zones.

In my case, I found that the issue was that the default timefunc in the sched.scheduler initializer is not time.time (as in the example), but rather is time.monotonic. time.monotonic does not make any sense for "absolute" time schedules as, from the docs, "The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid."

The solution for me was to initialize the scheduler as

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

It is unclear whether your time_module.time is actually time.time or time.monotonic, but it works fine when I initialize it properly.




回答6:


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

Just looking for a Time of Day / Date event trigger: as long as the date "string" is tied to an updated "time" string, it works as a simple TOD function. You can extend the string out to a date and time.

whether its lexicographical ordering or chronological order comparison, as long as the string represents a point in time, the string will too.

someone kindly offered this link:

String Comparison Technique Used by Python



来源:https://stackoverflow.com/questions/11523918/python-start-a-function-at-given-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!