Python cung cấp bộ lập lịch chung để chạy tác vụ tại thời điểm cụ thể. Dùng module schedule. Hàm every thiết lập lịch trình.
Cú pháp
schedule.every(n).[timeframe] n: khoảng thời gian. timeframe: seconds, hours, days, hoặc tên thứ (Sunday, Monday...)
Ví dụ: Lấy giá Bitcoin định kỳ
Dùng API CoinDesk, module requests gọi API, time.sleep giữ chương trình chạy chờ phản hồi.
import schedule
import time
import requests
URL = "https://api.coindesk.com/v1/bpi/currentprice.json"
data = requests.get(URL).json()
def fetch_bitcoin():
print("Getting Bitcoin Price")
result = data['bpi']['USD']
print(result)
def fetch_bitcoin_by_currency(x):
print("Getting bitcoin price in: ", x)
result = data['bpi'][x]
print(result)
# Lịch trình
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)
Kết quả (chạy liên tục):
Getting Bitcoin Price {'code': 'USD', 'symbol': '$', 'rate': '7,069.1967', ...}
Getting bitcoin price in: GBP {'code': 'GBP', 'symbol': '£', 'rate': '5,279.3962', ...}
Getting Bitcoin Price {...}
Getting bitcoin price in: EUR {'code': 'EUR', 'symbol': '€', 'rate': '6,342.4196', ...}
...