2013-04-02 58 views
1

我有两个芹菜实例。我希望能够通过电子邮件,推送等方式通知特定事件的所有用户。但是,我想确保所有用户只会收到一次通知。是否有一个如何循环访问用户并保证每个用户都被联系一次的例子?多个实例的Django芹菜问题

我的解决方案是简单地将用户标记为已收到通知......但这样做效率很低。并且可能存在用户在标记被保存时得到通知的情况。

我试着阅读关于这个如下:

http://docs.celeryproject.org/en/latest/userguide/routing.html

http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html

[编辑]

通过2个实例我的意思是1名工人在两个EC2的,所以2名工人。

回答

0

你看过这个吗? Ensuring a task is only executed one at a time

尽管我认为你的方法很好,但是将它存储到数据库中的方式是slow,你应该将它缓存起来以便很快地放置它。作为一个简单的设置,您可以在发送电子邮件之前缓存电子邮件(散列)。如果缓存已经存在,则不要发送电子邮件。

所以这会是这样的

from hashlib import md5 
from django.core.cache import cache 
from celery import task 

# 1 day because I expect that the whole email task finish within a day 
# But the same email may be send out if executed on the next day. 
LOCK_TIME = 24 * 60 * 60 

@task 
def notify_user(email): 
    uid = md5(email).hexdigest() 

    # This will return False if the uid already exists in the cache 
    if cache.add(uid, 'notified', LOCK_TIME): 
     send_mail("Subject", "Message", None, [email,]) 

NB:我想删除可能没有必要缓存。由于您只关心发送一次,直到过期。

+0

缓存不可靠吗? – KVISH

+0

您只需确保服务器永不死亡。这可能是您将旗子存入数据库的另一种方法的权衡 – Yeo