我正在开发一个Django应用程序。我有一个API端点,如果请求该端点,必须执行一个需要重复几次的函数(直到满足某个条件为止)。目前我的处理方式是 -
虽然我知道这是一种可怕的方法,我不应该阻塞2秒钟,但我无法想出其他解决方案。等待4秒后,这种方法可以运行。但我希望有一些东西能够在后台保持循环运行,并在some_fn返回True时停止。(此外,some_fn肯定会返回True)
编辑 -
阅读Oz123的回答给了我一个想法,似乎可以解决问题。这是我所做的 -
这对我来说很有效。它很简单,但我不知道多线程与Django结合使用的效率如何。
如果有人能指出其中的缺点,那么欢迎批评。
def shut_down(request):
# Do some stuff
while True:
result = some_fn()
if result:
break
time.sleep(2)
return True
虽然我知道这是一种可怕的方法,我不应该阻塞2秒钟,但我无法想出其他解决方案。等待4秒后,这种方法可以运行。但我希望有一些东西能够在后台保持循环运行,并在some_fn返回True时停止。(此外,some_fn肯定会返回True)
编辑 -
阅读Oz123的回答给了我一个想法,似乎可以解决问题。这是我所做的 -
def shut_down(params):
# Do some stuff
# Offload the blocking job to a new thread
t = threading.Thread(target=some_fn, args=(id, ), kwargs={})
t.setDaemon(True)
t.start()
return True
def some_fn(id):
while True:
# Do the job, get result in res
# If the job is done, return. Or sleep the thread for 2 seconds before trying again.
if res:
return
else:
time.sleep(2)
这对我来说很有效。它很简单,但我不知道多线程与Django结合使用的效率如何。
如果有人能指出其中的缺点,那么欢迎批评。