반응형

<참고> https://coding-kindergarten.tistory.com/164

 

python, 특정 함수 주기적 실행 예제 2

 

다음처럼 schedule 패키지를 설치하고 예제를 진행합니다.

 

pip3 install schedule 

 

[소스 코드] worker2.py

import schedule
import time
timer = 0
def worker1():
    print("1초마다 알람!")
def worker2(text):
    global timer
    print(text, timer)
# 스케줄 작업 예약 
job1 = schedule.every(1).seconds.do(worker1)
job2 = schedule.every(5).seconds.do(worker2,'5초마다 알람!')
while True:
    schedule.run_pending()  # 예약된 모든 작업을 실행
    time.sleep(1)
    timer = timer + 1
    if timer > 10:  # 10초 지나면 종료 
        schedule.cancel_job(job1)  # 예약 작업 취소
        schedule.cancel_job(job2)  # 예약 작업 취소
        break

 

[실행 결과]
1초마다 알람!
1초마다 알람!
1초마다 알람!
1초마다 알람!
5초마다 알람! 5
1초마다 알람!
1초마다 알람!
1초마다 알람!
1초마다 알람!
1초마다 알람!
5초마다 알람! 10
1초마다 알람!

반응형

+ Recent posts