Python为我们提供了一个通用调度程序,可以在特定时间运行任务。我们将使用一个名为schedule的模块。在此模块中,我们使用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模块每隔几秒钟获取一次bitcon的价格。我们还使用coindesk提供的api。为此,我们将使用请求模块。我们还需要时间模块,因为当响应延迟时,我们需要允许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}