我在3台集群计算机上安装了celery + rabbitmq。我还创建了一个任务,该任务根据文件中的数据生成一个正则表达式,并使用该信息来解析文本。但是,我希望每个工人生成文件的读取过程仅完成一次,而不是每次as任务执行时都完成。
from celery import Celery
celery = Celery('tasks', broker='amqp://localhost//')
import re
@celery.task
def add(x, y):
return x + y
def get_regular_expression():
with open("text") as fp:
data = fp.readlines()
str_re = "|".join([x.split()[2] for x in data ])
return str_re
@celery.task
def analyse_json(tw):
str_re = get_regular_expression()
re.match(str_re,tw.text)
在上面的代码中,我想打开文件并将每个工人的输出读入字符串一次,然后任务analyse_json应该只使用字符串。
任何帮助将不胜感激,
谢谢,阿米特
将呼叫放在模块级别的get_regular_expression
:
str_re = get_regular_expression()
@celery.task
def analyse_json(tw):
re.match(str_re, tw.text)
第一次导入模块时,它将仅被调用一次。
另外,如果一次只能运行一个工作实例(例如CUDA),则必须使用-P solo选项:
celery worker --pool solo
适用于芹菜4.4.2。