Python은 특정 시간에 작업을 실행할 수 있는 강력한 스케줄링 기능을 제공합니다. 이 글에서는 schedule 모듈을 활용하여 원하는 주기마다 작업을 반복 실행하는 방법을 알아보겠습니다. schedule 모듈의 핵심 함수인 every()를 사용하면 단 몇 줄의 코드로도 다양한 형태의 스케줄을 손쉽게 구성할 수 있습니다.
먼저 아래 명령어로 schedule 모듈을 설치합니다.
pip install schedule
기본 문법
Schedule.every(n).[timeframe]
여기서 n은 작업이 실행될 시간 간격을 의미하며, timeframe(시간 단위)에는 초(seconds), 분(minutes), 시간(hours), 일(days)뿐만 아니라 일요일(Sunday), 월요일(Monday) 같은 요일 이름도 지정할 수 있습니다. 예를 들어 schedule.every(10).minutes는 10분마다, schedule.every().monday는 매주 월요일에 작업을 실행하도록 설정합니다.
예제: 실시간 비트코인 가격 조회
다음 예제에서는 schedule 모듈을 사용하여 몇 초마다 비트코인 가격을 자동으로 가져오는 프로그램을 만들어 보겠습니다. 가격 데이터는 CoinDesk에서 제공하는 API를 통해 받아오며, HTTP 요청을 위해 requests 모듈을 사용합니다. 또한 API 응답이 지연될 때 프로그램이 대기 상태를 유지할 수 있도록 time 모듈의 sleep 기능도 함께 활용합니다.
import schedule
import time
import requests
Uniform_Resource_Locator = "https://api.coindesk.com/v1/bpi/currentprice.json"
data = requests.get(Uniform_Resource_Locator)
input = data.json()
def fetch_bitcoin():
print("Getting Bitcoin Price")
result = input['bpi']['USD']
print(result)
def fetch_bitcoin_by_currency(x):
print("Getting bitcoin price in: ", x)
result = input['bpi'][x]
print(result)
# 스케줄 등록
schedule.every(4).seconds.do(fetch_bitcoin)
schedule.every(7).seconds.do(fetch_bitcoin_by_currency, 'GBP')
schedule.every(9).seconds.do(fetch_bitcoin_by_currency, 'EUR')
while True:
schedule.run_pending()
time.sleep(1)위 코드를 실행하면 4초마다 USD 가격이, 7초마다 GBP(영국 파운드) 가격이, 9초마다 EUR(유로) 가격이 순차적으로 출력되며, 이 과정은 프로그램을 종료할 때까지 무한히 반복됩니다.
실행 결과
Getting Bitcoin Price
{'code': 'USD', 'symbol': '$', 'rate': '7,069.1967', 'description': 'United States Dollar', 'rate_float': 7069.1967}
Getting bitcoin price in: GBP
{'code': 'GBP', 'symbol': '£', 'rate': '5,279.3962', 'description': 'British Pound Sterling', 'rate_float': 5279.3962}
Getting Bitcoin Price
{'code': 'USD', 'symbol': '$', 'rate': '7,069.1967', 'description': 'United States Dollar', 'rate_float': 7069.1967}
Getting bitcoin price in: EUR
{'code': 'EUR', 'symbol': '€', 'rate': '6,342.4196', 'description': 'Euro', 'rate_float': 6342.4196}
Getting Bitcoin Price
{'code': 'USD', 'symbol': '$', 'rate': '7,069.1967', 'description': 'United States Dollar', 'rate_float': 7069.1967}참고 사항
예제에 사용된 CoinDesk BPI API는 서비스가 중단되었거나 응답 형식이 변경되었을 수 있습니다. 최신 환경에서 테스트한다면 CoinGecko나 Binance 공개 API처럼 현재 운영 중인 암호화폐 시세 API로 URL만 교체하면 동일한 로직으로 그대로 활용할 수 있습니다. 또한 무한 루프(while True) 안에서 schedule.run_pending()이 대기 중인 작업을 계속 확인하고, time.sleep(1)이 CPU 사용량을 낮추며 1초 단위로 체크하는 구조라는 점도 함께 기억해 두시기 바랍니다.