Python

Schedule Job 설정하기

CodePoetry 2016. 7. 17. 18:56

프로그램 실행 상태에서 매일 정해진 시간마다 한번씩 특정 함수를 실행시키고 싶었다.

Running 상태이기 때문에 Cron Job과는 차이가 있지만 Thread로 접근하는 것이 옳은 듯 했다.

-       Schedule : https://github.com/dbader/schedule


Schedule Threading 모듈을 이용하여 간단히 해결 할 수 있었다.

(Schedule만 가지고는 scheduling job 외에 다른 코드를 실행할 수 없으므로 이것을 Thread로 실행 시켜야 한다)



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import schedule # schedule 모듈은 generic이 아니므로 pip로 인스톨해야 함
import threading
 
alarm_thread = threading.Thread(target=schedule_alarm)
alarm_thread.start()
print 'I want this, too' # threading을 사용하지 않으면 이 라인을 출력할 수 없다.
 
def schedule_alarm():
    half_day_seconds = 12 * 60 * 60
    schedule.every().day.at("17:00").do(schedule_job)
    while True:
        schedule.run_pending() # pending된 Job을 실행
        time.sleep(half_day_seconds)
 
def schedule_job():
    # 하고 싶은 Job
cs