Python gives us a generic scheduler to run tasks at specific times. We will use a module called schedule. In this module we use the every function to get the desired schedules. Below is the features available with the every function..
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.
Example
In the below example we will see fetch the price of bitcon in every few seconds by using the schedule module. We also use the api provided by coindesk. For that purpose we will use the requests module. We will also need the time module as we need to allow the sleep function to keep the program running and wait for the api to respond, when there is delay in reponse.
Example
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)
Running the above code gives us the following result
Output
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}