自创建对象24小时后如何删除对象 [英] How to delete an object after 24hrs since creation of the same
本文介绍了自创建对象24小时后如何删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
自创建该实例以来,我想在24小时后删除该实例
I want to delete an instance after 24 hours since that instance has been created how to do that with celery
创建后如何启动计时器实例?
How can i start the "TIMER" after the creation of an instance?
我想要Snapchat
I want something like Snapchat
推荐答案
您将不得不使用django-celery-beat来执行定期任务:
http://docs.celeryproject.org/en/latest/userguide/periodic-tasks。 html#beat-custom-schedulers
You will have to use django-celery-beat for periodical tasks: http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers
老实说,我会创建一个每3-5分钟运行一次的芹菜任务。
I would honestly create a celery task that would run every 3-5 minutes.
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())
这篇关于自创建对象24小时后如何删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文