[英]Python : class programming and queuing
我面臨一個問題。 我找到了一個我在下面解釋的解決方案,但我想要一些建議來解決它。
這是問題所在:
我有一個名為Item的 class object 。 這個Item有一個方法,調用make_request在服務器上發出GET請求,並保存結果。 現在,我已經實現了 3項object 調用make_request 。 Item對象將每 3 分鍾調用一次該方法,但這些make_requests必須比前一個對象的調用延遲 1 分鍾。
例子:
我實際上做的是一個while循環,我在其中檢查時間分鍾並調用正確的對象的方法。
from datetime import datetime
Item0 = Item(name="Item0")
Item1 = Item(name="Item1")
Item2 = Item(name="Item2")
while True:
if str(datetime.now().time.minute[-1]) in ['0', '3', '6']:
Item0.make_request()
if str(datetime.now().time.minute[-1]) in ['1', '4', '7']:
Item1.make_request()
if str(datetime.now().time.minute[-1]) in ['2', '5', '8']:
Item2.make_request()
這是一個解決方案,但它不干凈,我不喜歡它。 它也缺少 1 分鍾。 我正在考慮使用隊列。
我在等你的建議:)
編輯:更強大的東西
非常感謝您的回答。 我為第一個問題找到了一個很好的解決方案。
現在,我問自己是否可以在相同的上下文中使用隊列。 這個想法是獨立於前一個make_request 的結果調用 make_request 。
例如:在 14:00:00 我調用Item0.make_request 。 不幸的是,獲得Item0.make_request的結果需要 60 多秒,但我希望在 14:01:00 獨立調用我的Item1.make_request 。
有時會發生
通常,當您有許多項目要完成相同的事情時,最好將它們保存在一個列表中:
items = [Item(name="Item0"), Item(name="Item1"), Item(name="Item2")]
然后,不需要特殊的邏輯來查看當前分鍾。 只需延遲 1 分鍾按順序運行它們:
while True:
for item in items:
item.make_request()
time.sleep(60) # 60 seconds
有一個缺點,你可能關心也可能不關心:事實上,兩個請求之間的時間將是 60 秒加上make_request()
所花費的時間。 有辦法避免這種情況,但也許你不關心這些細節。
我想出了一些矯枉過正的東西,可以根據您的需要進行配置。
import time
# Assuming your class
class Item:
def __init__(self, name, number_of_ticks_to_act_in, *args, **kawrgs):
self.name = name
self.number_of_ticks_to_act_in = number_of_ticks_to_act_in
def make_request(self):
print(f"Making a requests from {self.name}")
# Item0 and Item1 will post every 2 mins and Item2 every 3 mins.
items = [Item("Item0", 2), Item("Item1", 2), Item("Item2", 3)]
# ?: Your configs
seconds_per_tick = 60 # Every tick can be in every 60 seconds or how you want it.
ticks_passed = 0 # This is a counter to keep track of ticks passed.
max_ticks_item = max(items, key=lambda i: i.number_of_ticks_to_act_in) # The counter gets set back to 0 once the max ticks that you stated have exceeded, this will let you run the code forever and never have to worry about the number surpassing int size. Overkill.
is_condition_met = True # You can set a condition to stop your forever while loop
while is_condition_met:
# The counter is reset if it exceeds your max ticks.
if ticks_passed >= max_ticks_item.number_of_ticks_to_act_in:
ticks_passed = 0
ticks_passed += 1
time.sleep(seconds_per_tick)
# Only Items with the same tick will get executed, this lets you have 2 or more Items of the same tick.
for item in filter(lambda x: ticks_passed % x.number_of_ticks_to_act_in == 0,
items):
item.make_request()
希望這不是太復雜。 盡可能多地添加評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.