[英]Set timer for a Django view execution
我正在努力阻止 Django 視圖在一小時內執行多次。 換句話說,如果 function 在 15:00 運行,則所有用戶的所有未來請求都應被忽略,直到 17:00 允許再次運行。
嘗試使用計時器,但每次調用視圖時都會重置。 也許有人可以指出我正確的方向? 謝謝!!!
import threading as th
def hello():
print("hello, world")
def webhook(request):
tm = th.Timer(3600, hello)
if request.method == 'POST' and not tm.is_alive():
tm.start()
code_to.ecexute()
return HttpResponse("Webhook received!")
最終,這就是我所做的,它似乎工作正常。 我實際上需要它每天運行不超過一次,因此有以下條件。
感謝所有的建議!!!
def webhook2 (request):
today = datetime.now().date()
with open('timestamp.txt') as f:
tstamp = f.read()
last_run = datetime.strptime(tstamp, '%Y-%m-%d')
last_run_date = datetime.date(last_run)
print ("last run: " + str(last_run_date))
if last_run_date < today:
file = open("timestamp.txt" ,"w")
file.write(str(today))
file.close()
if request.method == 'POST':
msg = str(request.body)
final_msg=msg[2:-1]
print("Data received from Webhook is: ", request.body)
# creates a google calendar event
function_logic()
return HttpResponse("Webhook received! Event added to calendar")
else:
print ("we already have a record for today")
return HttpResponse("Not adding a record. We already have one for today.")
您的計時器每次都會被重置,因為它位於每次發出請求時都會執行的 function 內。 您應該嘗試全局設置計時器,例如在 function 之外。 (請注意,當您的腳本重新運行時,計時器將再次重置)。
import threading as th
def hello():
print("hello, world")
tm = None
def webhook(request):
# check here if timer is dead then process the request.
if timer_is_dead || tm is None:
# accessing global value and setting it for first time
if tm is None:
global tm
tm = th.Timer(3600, hello)
tm.start()
if request.method == 'POST' and not tm.is_alive():
code_to.ecexute()
# start timer again for next hour
return HttpResponse("Webhook received!")
else:
return HttResponse("Not Allowed")
編輯:處理第一個請求,然后啟動計時器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.