我必须安排一些看起来很复杂的任务才能并行运行。它们不相互依赖,并且函数需要3个参数。
我已经尝试使用chain,map和starmap方法。使用链,我会收到此错误:
[2019-04-23 15:28:00,991: ERROR/PoolWorker-3] Task proj.apps.tasks.generate[112a7426-5ac3-4cd6-8416-5591c3c018a3] raised unexpected: TypeError('get expected at least 1 arguments, got 0',)
Traceback (most recent call last):
File ".../local/lib/python2.7/site-packages/celery/app/trace.py", line 367, in trace_task
R = retval = fun(*args, **kwargs)
File ".../local/lib/python2.7/site-packages/celery/app/trace.py", line 622, in __protected_call__
return self.run(*args, **kwargs)
File ".../tasks.py", line 966, in generate
return res.get()
TypeError: get expected at least 1 arguments, got 0
我无法使用map
传递所有参数,并且使用starmap
会同时启动所有任务。
[2019-04-23 15:48:00,991: INFO/MainProcess] Received task: generate[..]
[2019-04-23 15:48:00,991: INFO/MainProcess] Received task: generate[..]
[2019-04-23 15:48:00,991: INFO/MainProcess] Received task: generate[..]
任务示例:
@shared_task
def generate(field1, field2, field3=None):
if field3 is not None:
return field1 + field2 + field3
return field1 + field2
使用链的代码:
res = chain(generate.s(i, 5, j) for i in array1 for j in array2)
return res.get()
使用星图的代码:
arguments = [(i, 4, j) for i in array1 for j in array2]
~generate.starmap(arguments)
答案 0 :(得分:0)
如果任务是真正独立的,则应使用.si
而不是.s
:
tasks = chain(generate.si(i, 5, j) for i in array1 for j in array2)
res = tasks()
return res.get()
答案 1 :(得分:0)
我所需要做的就是制作一条链,如下所示:
res = chain(generate(i, 2, j)for i in array1 for j in array2)()
return res.get()
然后使用设置最大线程数的附加参数运行celery
celery -A tasks worker --concurrency=1