Python ให้ตัวจัดกำหนดการทั่วไปแก่เราเพื่อเรียกใช้งานในเวลาที่กำหนด เราจะใช้โมดูลที่เรียกว่ากำหนดการ ในโมดูลนี้ เราใช้ทุกฟังก์ชันเพื่อรับตารางเวลาที่ต้องการ ด้านล่างนี้เป็นคุณสมบัติที่ใช้ได้กับทุกฟังก์ชั่น..
ไวยากรณ์
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.
ตัวอย่าง
ในตัวอย่างด้านล่าง เราจะเห็นการดึงราคาของ bitcon ในทุก ๆ สองสามวินาทีโดยใช้โมดูลกำหนดการ เรายังใช้ API ของ coindesk เพื่อจุดประสงค์นั้น เราจะใช้โมดูลคำขอ นอกจากนี้เรายังต้องการโมดูลเวลาเนื่องจากเราต้องอนุญาตให้ฟังก์ชันสลีปเพื่อให้โปรแกรมทำงานต่อไปและรอให้ 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}