【问题标题】:How to delete an object after 24hrs since creation of the same创建对象后 24 小时后如何删除对象
【发布时间】:2018-03-30 17:26:16
【问题描述】:

我想在创建实例后 24 小时后删除该实例如何使用 celery 执行此操作

创建实例后如何启动“TIMER”?

我想要 Snapchat 之类的东西

【问题讨论】:

标签: django database django-models celery


【解决方案1】:

取决于规模和您的需求。

您必须使用 django-celery-beat 来执行周期性任务: http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers

老实说,我会创建一个每 3-5 分钟运行一次的 celery 任务。

models.py

   class Foo(models.model):
       created_at = models.DateTimeField(auto_add_now=True)
       expiration_date = models.DateTimeField()

views.py

import datetime
from django.utils import timezone

def add_foo():
    # Create an instance of foo with expiration date now + one day
    Foo.objects.create(expiration_date=timezone.now() + datetime.timedelta(days=1))

tasks.py

from celery.schedules import crontab
from celery.task import periodic_task
from django.utils import timezone

@periodic_task(run_every=crontab(minute='*/5'))
def delete_old_foos():
    # Query all the foos in our database
    foos = Foo.objects.all()

    # Iterate through them
    for foo in foos:

        # If the expiration date is bigger than now delete it
        if foo.expiration_date < timezone.now():
            foo.delete()
            # log deletion
    return "completed deleting foos at {}".format(timezone.now())

【讨论】:

  • 有没有其他方法可以做到这一点,没有芹菜。只是想知道选项;)或任务排队是唯一的方法
  • @manishadwani 您的问题询问如何通过celery 完成并具有celery 标签。确保编辑问题,使其也反映这一点。其他可能的解决方案是设置一个 cron 作业,该作业将通过 bash 运行 manage.py 命令,这将做同样的事情。 Celery 是为这些用例而构建的。我建议你通过芹菜来做这件事,但如果其他人有其他选择,请等待他们回应! :)
  • 感谢您的快速回复,我会看看这个
  • 没问题,如果您需要更多帮助或编辑问题,请标记我!
  • @user1 不确定你使用的是什么语言或你在暗示什么(虽然我真的说“你很有趣”但作为一个贬义词),但享受国旗并祝你有美好的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
  • 2020-07-30
  • 2021-07-31
  • 2020-07-06
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
相关资源
最近更新 更多