python - 芹菜周期性任务不访问模块变量
问题描述
我有一个配置良好的芹菜并与 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)。
推荐阅读
- python - 在 numpy 上测试位
- javascript - 浏览器 IE11 JavaScript 让 [...document.querySelectorAll 语法错误
- flutter - ChangeNotifierProvider 显示灰屏
- python - 玩家在 pygame 中使用 player.jump 只跳跃一次
- vue.js - Asp.net core 3.1 后端没有从 cookie 中获取身份
- excel - excel最小值不同于0,使得下一个值为0
- php - 如何在 laravel 中获取 url 参数?
- swift - 如何摆脱 SwiftUI TextFields 周围的蓝色选择边框?
- python - 我们可以使用 Python 中的 Quandl 库获得印度股市的股票调整价格吗?
- python-3.x - 如何使用python查找字符串中重复次数第二多的字符