防止芹菜运行我的Django应用程序线程
我有一个Django应用程序,并且正在使用芹菜(带Redis)在后台运行处理任务。此外,我还有一个python线程,该线程是我的Django应用程序的一部分进行一些定期检查。令人惊讶的是,当我开始芹菜时,我看到我的线程也是芹菜的一部分。我想防止这种行为,只有一个线程的一个实例,并将其作为Django应用程序的一部分。如何防止它在芹菜中运行?
我在新创建的应用程序上测试了它,并查看完全相同的行为:
settings.py:
...
CELERY_BROKER_URL = 'redis://localhost:6379/1'
__ init __. py:
from threading import Thread
from time import sleep
from .celery import app as celery_app
__all__ = ('celery_app',)
def mythread():
while True:
print("thread is running")
sleep(10)
new_thread = Thread(target=mythread, daemon=True)
new_thread.start()
celery.py:
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')
app = Celery('myapp')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
芹菜输出:
...
[2022-06-15 16:21:49,923: INFO/MainProcess] Events of group {task} enabled by remote.
[2022-06-15 16:21:49,958: WARNING/MainProcess] thread is running
[2022-06-15 16:21:59,968: WARNING/MainProcess] thread is running
I have a Django app and I am using celery (with redis) for running processing tasks in the background. In addition, I have a python thread which runs some periodic checks as part of my Django app. Surprisingly, when I am starting celery I see my thread is also running as part of celery. I would like to prevent this behavior and have only one instance of my thread and have it as part of my Django app. How can I prevent it from running in celery?
I tested it on a newly created app and see the exact same behavior:
settings.py:
...
CELERY_BROKER_URL = 'redis://localhost:6379/1'
__init__.py:
from threading import Thread
from time import sleep
from .celery import app as celery_app
__all__ = ('celery_app',)
def mythread():
while True:
print("thread is running")
sleep(10)
new_thread = Thread(target=mythread, daemon=True)
new_thread.start()
celery.py:
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')
app = Celery('myapp')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
Celery output:
...
[2022-06-15 16:21:49,923: INFO/MainProcess] Events of group {task} enabled by remote.
[2022-06-15 16:21:49,958: WARNING/MainProcess] thread is running
[2022-06-15 16:21:59,968: WARNING/MainProcess] thread is running
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我实施了这种解决方法,以防止线程在芹菜下运行:
如果有更清洁的解决方案,我很乐意采用它。
I implemented this workaround in order to prevent the thread from running under celery:
If there is a cleaner solution, I will be happy to adopt it.