Python-Uruchom funkcję w danym momencie
Jak mogę uruchomić funkcję w Pythonie, w danym momencie?
Na przykład:
run_it_at(func, '2012-07-17 15:50:00')
I uruchomi funkcję func
w dniu 2012-07-17 15:50:00.
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, ())
Co mogę zrobić? 6 answers
Czytanie dokumentów z http://docs.python.org/py3k/library/sched.html :
Wychodząc z tego musimy wypracować opóźnienie (w sekundach)...
from datetime import datetime
now = datetime.now()
Następnie użyj datetime.strptime
, aby przeanalizować '2012-07-17 15: 50: 00' (zostawię ci łańcuch formatu)
# 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()
Możesz następnie użyć delay
, aby przejść do instancji threading.Timer
, np:
threading.Timer(delay, self.update).start()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-17 14:30:04
Spójrz na zaawansowany Scheduler Pythona, APScheduler: http://packages.python.org/APScheduler/index.html
Mają przykład tylko tego zastosowania: 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'])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-27 21:31:50
Oto aktualizacja odpowiedzi stephenbeza na wersję 3.5 apschedulera używającego Pythona 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()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-28 01:00:58
Natknąłem się na ten sam problem: nie udało mi się zarejestrować zdarzeń czasu bezwzględnego za pomocą sched.enterabs
, aby były rozpoznawane przez sched.run
. sched.enter
pracował dla mnie, jeśli obliczyłem delay
, ale jest niewygodne w użyciu, ponieważ chcę, aby praca działała w określonych porach dnia w poszczególnych strefach czasowych.
W moim przypadku problem polegał na tym, że domyślnym timefunc
w inicjalizatorze sched.scheduler
nie jest time.time
(jak w przykładzie ), ale raczej time.monotonic
. time.monotonic
nie ma sensu dla "absolutnych" harmonogramów czasowych, ponieważ, z docs , " punkt odniesienia zwracanej wartości jest niezdefiniowany, tak że ważna jest tylko różnica między wynikami kolejnych wywołań."
Rozwiązaniem dla mnie było zainicjowanie schedulera jako
scheduler = sched.scheduler(time.time, time.sleep)
Nie jest jasne, czy Twoja time_module.czas to właściwie czas.czas lub czas.monotoniczny, ale działa dobrze, gdy zainicjuję go prawidłowo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-10 13:54:49
Może warto zainstalować tę bibliotekę: https://pypi.python.org/pypi/schedule , w zasadzie pomaga zrobić wszystko, co właśnie opisałeś. Oto przykład:
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)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-21 01:38:29
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
Po prostu szukam czasu dnia / daty zdarzenia wyzwalacza: tak długo, jak data "ciąg" jest powiązany ze zaktualizowanym ciągiem "czas", działa jako prosta funkcja TOD. Możesz rozszerzyć łańcuch do daty i godziny.
Czy jego uporządkowanie leksykograficzne czy porównanie porządku chronologicznego, tak długo, jak łańcuch reprezentuje punkt w czasie, łańcuch będzie również.
Ktoś uprzejmie zaproponował ten link:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-05 01:38:35