Computer >> Máy Tính >  >> Lập trình >> Python

Bộ lập lịch sự kiện bằng Python

Python cung cấp cho chúng ta một bộ lập lịch biểu chung để chạy các tác vụ vào những thời điểm cụ thể. Chúng tôi sẽ sử dụng một mô-đun được gọi là lịch trình. Trong mô-đun này, chúng tôi sử dụng mọi chức năng để có được các lịch trình mong muốn. Dưới đây là các tính năng có sẵn với mọi chức năng ..

Synatx

Schedule.every(n).[timeframe]
Here n is the time interval.
Timeframe can be – seconds, hours, days or even name of the
Weekdays like – Sunday , Monday etc.

Ví dụ

Trong ví dụ dưới đây, chúng ta sẽ thấy giá của bitcon trong vài giây một lần bằng cách sử dụng mô-đun lịch trình. Chúng tôi cũng sử dụng api do coindesk cung cấp. Vì mục đích đó, chúng tôi sẽ sử dụng mô-đun yêu cầu. Chúng tôi cũng sẽ cần mô-đun thời gian vì chúng tôi cần cho phép chức năng ngủ để giữ chương trình chạy và đợi api phản hồi, khi có sự chậm trễ trong phản hồi.

Ví dụ

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)
#time
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)

Chạy đoạn mã trên cho chúng ta kết quả sau

Đầu ra

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}