Python 中的事件调度程序

pythonserver side programmingprogramming更新于 2024/1/17 8:17:00

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。为此,我们将使用请求模块。我们还需要时间模块,因为我们需要允许睡眠函数保持程序运行并等待 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}

相关文章