在my models.py中,我有一个如何控制线程寿命的类:
class Repartidor(models.Model):
thread_active = models.BooleanField(default=False)
def launch_thread(self):
self.thread_active = True
self.save()
def kill_thread(self):
self.thread_active = False
self.save()
def get_thread_state(self):
if self.thread_active:
return True
else:
return False
在repartidor.py中,我声明线程:
class RepartidorThread(threading.Thread):
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None):
super(RepartidorThread, self).__init__()
self.target = target
self.name = name
def run(self):
repartidor = Repartidor.objects.get(pk=1)
while True:
condition = repartidor.get_thread_state()
if condition:
do_something()
time.sleep(1)
else:
pass
time.sleep(1)
并在wsgi.py中启动线程
from printers.repartidor import RepartidorThread
thread_repartidor = RepartidorThread(name='Thread_Repartidor')
thread_repartidor.start()
但是我有一个问题,我用get_thread_state()
读取repartidor.py中的条件,它返回True或False。如果我通过django_管理员或前端更改条件,数据库的值就会更新,我的所有项目都会读取新的值,线程除外,它总是读取第一个值。
如果我停止并启动服务器,线程将读取新的valor。为什么会这样
我解决了我的问题。在方法run()中,我在while循环的每次迭代中都会得到对象:
相关问题 更多 >
编程相关推荐