Home  >  Q&A  >  body text

python - Django如何监听启动,开启另外后台线程?

1. 无法启动的时候另外启动一个后台线程

2. 部分代码如下:

mqtt_bridge/__init__.py

# coding=utf8
from bridge import start
import threading

print 'import %s thread id: %s' % ('bridge.start', threading.current_thread().ident)
start()  # 重复启动啊

在Install apps里面加入模块名,在Django启动的时候会自动导入

INSTALLED_APPS = (
    # 'jet.dashboard',
    # 'jet',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Django rest framework
    'rest_framework',
    'rest_framework.authtoken',
    # my apps
    'mqtt_bridge'
)

3. 控制台输出:

import bridge.start thread id: 7124
bridge-54 INFO : MQTT client listen loop start! thread id: 8680
bridge-28 INFO : MQTT client connected with result code: 0
import bridge.start thread id: 8200
bridge-54 INFO : MQTT client listen loop start! thread id: 840
bridge-28 INFO : MQTT client connected with result code: 0
Performing system checks...

4. 很明显这个模块被导入了两次,模块里面的线程也是开启了两个,这样很耗费系统资源。

5. 其他解决办法只能去占有端口,然后判断是否已经启动,觉得太低效了。

参考:从Django启动守护进程

怪我咯怪我咯2741 days ago747

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:32:44

    If you want to perform some initialization work in the Django APP, you should customize the configuration class in the APP's app.py, and then rewrite the ready() method.

    Django application initialization process: https://docs.djangoproject.co...

    reply
    0
  • Cancelreply