매일 같은 시간에 작업을 수행하는 Python 스크립트
나는 매일 아침 01:00에 무언가를 하고 싶은 긴 파이썬 스크립트가 있습니다.
스케줄링된 모듈과 Timer 개체를 살펴보았지만 이를 위해 어떻게 사용해야 하는지 알 수 없습니다.
01:00에 간단한 파이썬 프로그램을 시작하려고 많은 시간을 보냈습니다.어떤 이유에서인지 cron을 실행할 수 없었고 APScheduler는 단순해야 할 것에 비해 다소 복잡해 보였습니다.스케줄 (https://pypi.python.org/pypi/schedule) 이 거의 맞는 것 같았습니다.
Python 라이브러리를 설치해야 합니다.
pip install schedule
이는 샘플 프로그램에서 수정한 것입니다.
import schedule
import time
def job(t):
print "I'm working...", t
return
schedule.every().day.at("01:00").do(job,'It is 01:00')
while True:
schedule.run_pending()
time.sleep(60) # wait one minute
작업 대신 자신의 기능을 사용하고 다음과 같은 작업을 수행하지 않고 실행해야 합니다.
nohup python2.7 MyScheduledProgram.py &
다시 부팅하면 다시 시작하는 것을 잊지 마십시오.
다음과 같이 할 수 있습니다.
from datetime import datetime
from threading import Timer
x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
def hello_world():
print "hello world"
#...
t = Timer(secs, hello_world)
t.start()
이렇게 하면 함수가 실행됩니다(예:다음 날 새벽 1시에 hello_world).
편집:
@PaulMag에서 제안한 것처럼, 보다 일반적으로 월말에 도달하여 해당 월의 날짜를 재설정해야 하는지 여부를 감지하기 위해 이 컨텍스트에서 y의 정의는 다음과 같습니다.
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
이 수정 사항을 사용하면 가져오기에 시간 델타를 추가해야 합니다.다른 코드 라인은 동일하게 유지됩니다.따라서 total_seconds() 함수를 사용하는 전체 솔루션은 다음과 같습니다.
from datetime import datetime, timedelta
from threading import Timer
x=datetime.today()
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta_t=y-x
secs=delta_t.total_seconds()
def hello_world():
print "hello world"
#...
t = Timer(secs, hello_world)
t.start()
APS 스케줄러는 당신이 원하는 것일 수 있습니다.
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'])
# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])
https://apscheduler.readthedocs.io/en/latest/
예약 중인 기능에 이 기능을 추가하여 다른 실행을 예약할 수 있습니다.
저는 업무상 비슷한 것이 필요했습니다.제가 작성한 코드는 다음과 같습니다.다음 날을 계산하고 시간을 필요한 대로 변경하며 현재 시간과 다음 예약 시간 사이의 초를 찾습니다.
import datetime as dt
def my_job():
print "hello world"
nextDay = dt.datetime.now() + dt.timedelta(days=1)
dateString = nextDay.strftime('%d-%m-%Y') + " 01-00-00"
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay,my_job,()).start()
언급URL : https://stackoverflow.com/questions/15088037/python-script-to-do-something-at-the-same-time-every-day
'programing' 카테고리의 다른 글
나란히 2개의 다이브 - 유체 디스플레이 (0) | 2023.07.28 |
---|---|
치명적인 예외가 발생했을 때 php가 500을 반환하도록 하려면 어떻게 해야 합니까? (0) | 2023.07.28 |
검색 엔진 Lucene 대 데이터베이스 검색 (0) | 2023.07.28 |
iframe은 왜 이렇게 느립니까? (0) | 2023.07.28 |
소문자 및 대문자(jQuery 포함) (0) | 2023.07.28 |