RQ超时不会终止多线程作业

2024-06-05 23:03:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用pythonrq(在v0.5.6和v0.6.0上测试)运行多线程任务时遇到问题。在

把下面这段代码看作是我要实现的简化版本:

在东西.py在

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()

在主.py在

^{pr2}$

当执行main.py(当rqworker在后台运行时),作业会在5秒钟内按预期超时中断。在

问题是,当我设置一个包含线程(如MyThing().hello_task)的任务时,线程将永远运行,当5秒超时结束时什么也不会发生。在

如何使用RQ运行多线程任务,以便超时会杀死任务及其儿子、孙子和他们的妻子?在


Tags: 代码frompyself版本truehellotask
1条回答
网友
1楼 · 发布于 2024-06-05 23:03:27

当您运行t.join()时,hello_task线程阻塞并等待直到say_hello线程返回,因此不会从rq接收超时信号。您可以使用Thread.join,在等待线程完成运行的同时,使用设置的等待时间,允许主线程运行并正确接收超时信号。是这样的:

def hello_task(self):
    t = Thread(target=self.say_hello)
    t.start()
    while t.isAlive():
        t.join(1)  # Block for 1 second

这样,您还可以捕获超时异常并进行处理,如果您愿意:

^{pr2}$

相关问题 更多 >