我在使用pythonrq(在v0.5.6和v0.6.0上测试)运行多线程任务时遇到问题。在
把下面这段代码看作是我要实现的简化版本:
from threading import Thread
class MyThing(object):
def say_hello(self):
while True:
print "Hello World"
def hello_task(self):
t = Thread(target=self.say_hello)
t.daemon = True # seems like it makes no difference
t.start()
t.join()
当执行main.py
(当rqworker在后台运行时),作业会在5秒钟内按预期超时中断。在
问题是,当我设置一个包含线程(如MyThing().hello_task
)的任务时,线程将永远运行,当5秒超时结束时什么也不会发生。在
如何使用RQ运行多线程任务,以便超时会杀死任务及其儿子、孙子和他们的妻子?在
当您运行
t.join()
时,hello_task
线程阻塞并等待直到say_hello
线程返回,因此不会从rq接收超时信号。您可以使用Thread.join
,在等待线程完成运行的同时,使用设置的等待时间,允许主线程运行并正确接收超时信号。是这样的:这样,您还可以捕获超时异常并进行处理,如果您愿意:
^{pr2}$相关问题 更多 >
编程相关推荐