我正在尝试调用一个创建和使用和弦的方法,将该和弦用于另一个方法中构建的和弦。但是我无法按正确顺序调用回调函数。
#celery obj
app = Celery('tasks', backend=BACKEND, broker=BROKER)
以下是我用来测试这个的简单方法:
方法如下:
@app.task
def first_task(args):
return 'first_task'
@app.task
def first_body(args):
return 'first_body'
@app.task
def second_body(args):
return 'second_body'
@app.task
def third_body(args):
return 'third_body'
这是我创建和弦的方法:
@app.task
def simple_chord(args):
c = chord(group([first_task.s(args)]), body=first_body.s())
return c()
# this works as expected
# first_task -> first_body -> second_body -> third_body
def test_chords():
c = chord(group([chord(group([chord(group([first_task.s('foo')]),
body=first_body.s())]),
body=second_body.s())]),
body=third_body.s())
c.delay()
# this does not work as expected
# first_task -> second_body -> first_body -> third_body
def test_chords_2():
c = chord(group([chord(group([simple_chord.s('foo')]),
body=second_body.s())]),
body=third_body.s())
c.delay()
当我在一个地方构建和弦时,如
test_chords
中所示,它会按照我的预期执行(第一个任务 -> 第一个主体 -> 第二个主体 -> 第三个主体)。然而,我想能够在另一个和弦中获取我在simple_chord
方法中构建的和弦,就像在test_chords_2
中一样,但它不会等待first_body
被执行后再执行second_body
。相反,它按照以下顺序执行:第一个任务 -> 第二个主体 -> 第一个主体 -> 第三个主体。在工人控制台中我看到的是:
[2018-06-25 16:55:21,466: INFO/MainProcess] Received task: tasks.simple_chord[c78eb259-e1e1-4b4d-b053-247afce4d536]
[2018-06-25 16:55:21,660: INFO/MainProcess] Received task: tasks.first_task[fca138d2-c672-4299-a2ed-1bb5cacb66da]
[2018-06-25 16:55:21,685: INFO/ForkPoolWorker-1] Task tasks.simple_chord[c78eb259-e1e1-4b4d-b053-247afce4d536] succeeded in 0.19740361299773213s: <AsyncResult: c4db6bbf-d150-44db-a34e-99ea6bd71012>
[2018-06-25 16:55:21,688: INFO/MainProcess] Received task: tasks.second_body[afc32047-3239-4118-bb2c-c116f9a241bf]
[2018-06-25 16:55:23,340: INFO/ForkPoolWorker-1] Task tasks.first_task[fca138d2-c672-4299-a2ed-1bb5cacb66da] succeeded in 1.639255696994951s: 'first_task'
[2018-06-25 16:55:23,344: INFO/MainProcess] Received task: tasks.first_body[c4db6bbf-d150-44db-a34e-99ea6bd71012]
[2018-06-25 16:55:24,099: INFO/ForkPoolWorker-1] Task tasks.second_body[afc32047-3239-4118-bb2c-c116f9a241bf] succeeded in 0.7374479610007256s: 'second_body'
[2018-06-25 16:55:24,103: INFO/MainProcess] Received task: tasks.third_body[9a90c2da-cd03-4f55-9675-9194acd7d42f]
[2018-06-25 16:55:24,656: INFO/ForkPoolWorker-1] Task tasks.first_body[c4db6bbf-d150-44db-a34e-99ea6bd71012] succeeded in 0.5298690330091631s: 'first_body'
[2018-06-25 16:55:25,247: INFO/ForkPoolWorker-1] Task tasks.third_body[9a90c2da-cd03-4f55-9675-9194acd7d42f] succeeded in 0.5770523219980532s: 'third_body'
我的问题是如何最好地完成这样的事情?