[英]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.