如何在创建对象后 24 小时后删除对象



我想在创建实例 24 小时后删除该实例 如何使用芹菜做到这一点

创建实例后如何启动"定时器"?

我想要类似Snapchat的东西

取决于规模和您的需求。

你将不得不使用django-celery-beat进行周期性任务:http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers

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

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())

相关内容

  • 没有找到相关文章

最新更新