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 响应,当响应延迟时。

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

示例

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}

更新于:2019-12-23

已浏览 2 千多次

开启你的 职业生涯

通过完成课程获得认证

开始
广告