首页 > 解决方案 > 芹菜周期性任务不访问模块变量

问题描述

我有一个配置良好的芹菜并与 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 应用程序运行在一个微服务上,用于向用户发送提醒邮件。

标签: pythondjangocelery

解决方案


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

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


推荐阅读