본문 바로가기
python3 selenium

python schedule & Thread 사용 방법 및 예제

by Pymac 2023. 12. 8.
반응형

schedule은 Python에서 사용할 수 있는 간단하면서도 강력한 스케줄링 라이브러리 중 하나입니다.

이 라이브러리를 사용하면 주기적으로 작업을 실행하거나 특정 시간에 함수를 호출할 수 있습니다.

먼저, schedule 라이브러리를 설치해야 합니다. 아래 명령을 사용하여 설치할 수 있습니다:

 

pip install schedule

 

다음은 schedule 라이브러리를 사용한 간단한 예제입니다. 이 예제에서는 매 2초마다 현재 시간을 출력하는 작업을 스케줄링합니다.

mport schedule
import time

def job():
    print("현재 시간:", time.strftime("%Y-%m-%d %H:%M:%S"))

# 2초마다 job 함수를 실행하는 작업을 스케줄링
schedule.every(2).seconds.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

 

위 코드에서 schedule.every(2).seconds.do(job)은 2초 간격으로 job 함수를 실행하도록 스케줄링합니다. schedule.run_pending()은 예정된 작업이 있다면 실행하고, time.sleep(1)은 1초 동안 대기합니다.

또 다른 예제로는 매일 특정 시간에 특정 작업을 실행하는 경우입니다.

import schedule
import time

def daily_job():
    print("매일 정해진 시간에 실행되는 작업")

# 매일 오후 2시에 daily_job 함수를 실행하는 작업을 스케줄링
schedule.every().day.at("14:00").do(daily_job)

while True:
    schedule.run_pending()
    time.sleep(1)

 

이렇게 하면 매일 오후 2시에 daily_job 함수가 실행됩니다.

schedule을 사용하면 주기적인 작업을 쉽게 스케줄링할 수 있습니다. 더 복잡한 스케줄링도 가능하며, 자세한 내용은 schedule 라이브러리의 공식 문서를 참고하시기를 권장합니다.

 

아래는 Thread 에서 schedule 을 사용하는 예제입니다. 

 
import schedule
 
def start_crawling_schedule(self):
        # 매시간마다 작업 스케줄링
        schedule.every().hour.do(self.check_and_send_updates)
        # 매분마다 작업 스케줄링
        schedule.every().minute.do(self.check_and_send_updates)
        # 매초마다 작업 스케줄링
        schedule.every().second.do(self.check_and_send_updates)
        # 스케줄링 스레드 시작
        threading.Thread(target=self.schedule_jobs, daemon=True).start()

    def schedule_jobs(self):
        while True:
            schedule.run_pending()
            time.sleep(10)  # 필요에 따라 sleep 간격 조절
반응형