celery with rabbitmq 为什么要启动celery进程

celery with rabbitmq why to start the celery process

试图从 the following link

了解 celery 如何与 rabbitmq 一起工作

代码:

from celery import Celery

app=Celery('tasks',backend='amqp',broker='amqp://')

@app.task(ignore_result=True)
def print_hello():
    print 'hello'
    for i in xrange(2,222222):
        print i

print_hello()

问题:

  1. 运行宁celery worker -A celery_test -n 1.%h &有什么用?我可以直接 运行 python 脚本。

  2. 如果想在被调用的函数中读取结果怎么办:

    from celery import Celery
    
    app=Celery('tasks',backend='amqp',broker='amqp://')
    
    @app.task()
    def print_hello(n):
        print 'hello'
        for i in xrange(2,n):
            print i
        # continue the code from here after the above processing
    
  1. celery 的想法是任务在单独的进程中异步 运行,称为“工人”,可能在许多机器上。您安排任务的应用程序(您 运行 的 python 脚本)不需要知道关于您的设置的任何信息:工作人员实际 运行 的位置、他们的数量等。那是为什么你必须自己用 celery worker.

    启动工人

    在您的脚本中,您同步调用任务,因此它会立即执行,而不是在 rabbitmq 中排队并交给工作人员。在 Web 应用程序的上下文中,您需要以不同方式安排任务(请参阅有关 calling tasks 的 Celery 文档)。

  2. Celery 可以将任务的结果存储在 result storage.

问题 2:

from path.to module import print_hello

task_result = print_hello.apply_async((10,), {})
result = task_result.get()
  1. What is the use for running celery worker -A celery_test -n 1.%h &? I can run the python script directly.

你可以直接运行脚本,没错,但你必须手动完成。

芹菜是这样工作的:

  • 您有一名或多名工人运行正在某处;
  • 一个应用程序需要请求一个worker来完成一些任务。它将消息放入队列(在本例中为 RabbitMQ)。
  • Celery 收到消息并要求其中一名工作人员执行任务。

现在我当然省略了一些细节(Celery 提供了许多有趣的特性),我想说的是 Celery 是关于从应用程序启动任务到工作云。

因此,手动 运行ning 脚本没有任何好处。您应该远程启动任务以使 Celery 有用。

  1. What if want to read the result in the called function like, [...]

您必须删除 ignore_result=True(您已经删除了)。然后,一旦任务完成,您就可以从启动任务的应用程序中检索结果。摘自guide you are following

To check whether the task is complete, we can use the .ready method:

[...]

We can get the value by using the .get method.

请注意,.get 将为您提供任务的 return 值 ,而不是输出。您的 print_hello() 正在生成输出,但没有 returning 任何东西:.get 将 return None.

如果你想从其他地方获取结果(而不是从启动任务的应用程序),你可以使用 the task_id.