【问题标题】:Using global variables in Celery: What's the best approach?在 Celery 中使用全局变量:最好的方法是什么?
【发布时间】:2017-12-11 23:17:15
【问题描述】:

我正在使用 Django 1.10 和 Celery 编写应用程序。 我试图在 celery 中创建一个可以通过 Django 启动和停止的循环。

我的想法是这样的(很简单):

_run = False

def do_work():
  global _run
  while _run:
    # Do something

@app.task
def start():
  global _run
  _run = True
  do_work()

@app.task
def stop():
  global _run
  _run = False

问题是 celery 通常在 >1 个工作线程中运行,并且线程之间无法访问 _run。

问题:实现该功能的最佳方法是什么? 我正在考虑设置一个数据库变量,但恐怕这不是最好的方法。

【问题讨论】:

  • 这似乎是一个 XY 问题。为什么你想要一个循环?
  • 循环将从外部 API 轮询数据并填充系统数据库。我不明白你所说的“XY 问题”是什么意思。
  • 你为什么使用 Celery 任务?似乎是错误的用例

标签: python django celery


【解决方案1】:

一种可能的方法是创建将永远运行的任务,然后根据请求停止它。

from proj.celery import app
app.control.revoke(task_id)

http://docs.celeryproject.org/en/latest/faq.html#can-i-cancel-the-execution-of-a-task

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2010-10-12
    • 2011-12-01
    • 2014-01-27
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多