Python 中的事件排程程式
Python 為我們提供了一個通用排程程式,可在特定的時間執行任務。我們將使用一個名為 schedule 的模組。在此模組中,我們使用 every 函式獲取所需的排程。以下是 every 函式提供的功能。
語法
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.
示例
在下面的示例中,我們將看到使用 schedule 模組每隔幾秒獲取一次比特幣的價格。我們還將使用 coindesk 提供的 API。為此,我們將使用 requests 模組。我們還需要 time 模組,因為我們需要讓 sleep 函式保持程式執行並等待 API 響應,當響應延遲時。
示例
import schedule
import time
import requests
Uniform_Resource_Locator="http://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)執行以上程式碼將得到以下結果
輸出
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}
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP