redis Celery和弦中的任务总是按顺序执行吗?

q3qa4bjr  于 2023-02-15  发布在  Redis
关注(0)|答案(1)|浏览(162)

celery 和弦中的任务能保证按照它们开始的顺序执行吗?我重复了这个例子很多次,顺序都是一样的。从文档中,我解释说任务会并发发生,所以顺序是不可预测的。我添加了一个time.sleep(random()),结果仍然是True

# pip install celery
# docker run -d -p 6379:6379 redis

# app.py
import time
import random
from celery import Celery

app = Celery('tasks', broker='redis://localhost:6379')

app.conf.update(
    result_backend='redis://localhost:6379/0',
)
@app.task
def add(x, y):
    return x + y

@app.task()
def check_task_order(numbers):
    time.sleep(random.random())
    return numbers == sorted(numbers)

# start.py
from celery import chord
from app import add, tsum

print(chord(
    add.subtask((i, i)) for i in range(100)
)(tsum.subtask()).get())

# terminal 1:
celery -A app worker --loglevel=info

# terminal 2
python start.py
>> True
ef1yzkbh

ef1yzkbh1#

任务的执行顺序并不确定,因为它们是异步的。但是,返回值是按照任务的顺序给出的。
为了证明这一点,我更新了任务定义,发现tsum现在返回False而不是True。注意,我还将任务计数从100增加到1000。

@app.task
def add(x, y):
    return (x, time.time()) # Return the task number and current time

@app.task()
def tsum(numbers):
    time.sleep(random.random())
    # If the task return values sorted on the task number differs from the
    #   task return values sorted on the time they executed,
    #   we know that the execution order differs from the return order.
    return (
        numbers == sorted(numbers) and 
        numbers == sorted(numbers, key=lambda x: x[1])
    )

相关问题