芹菜周期性任务不访问模块变量

Celery periodic task not accessing module variables

我有一个配置良好的芹菜,可以与 django 一起使用。 在 post_save 信号上,我使用任务将新记录发送到集合 并使用另一个周期性任务,我正在尝试使用该集合。

from __future__ import absolute_import, unicode_literals
from celery import shared_task

class Data():
    def __init__(self):
        self.slotshandler = set()

global data
data = Data()

@shared_task
def ProcessMailSending(): #This is a periodic task, running every 30 seconds
    global data #This variable is always empty here
    while slotshandler:
        slot_instance = slotshandler.pop()
        print("sending mail for slot } to {} by mail {}".format(slot_instance .id,slot_instance .user,slot_instance .user_mail))

@shared_task
def UpdateSlotHandler(new_slot): #This is called by save_post django signal
    global data
    data.slotshandler.add(new_slot) #filling the set at each new record

问题是这个任务看不到我新添加的时间段。 请注意,此 django 应用程序 运行 在微服务上用于向用户发送提醒邮件。

不同的 celery 任务产生不同的进程,这些进程不共享对内存的访问。也就是说,您的全局在这些进程之间并不持久。当您的第一个任务完成时,所有与其进程关联的内存都会被刷新。您的第二个任务在内存中创建了一组全新的对象,包括您的全局变量。

您确实需要将数据保存在更持久的东西中,数据库或内存缓存(例如 Memcache)。