简体   繁体   English

如何在celery和django中为特定模型实例创建周期任务

[英]how to create periodictask in celery and django for an specific model instance

I have a Django model Person: 我有一个Django模型人:

class Person(models.Model):
    first_name = models.CharField(max_length=100, blank=False, null=False)
    last_name = models.CharField(max_length=100, blank=False, null=False)
    cellphone = models.CharField(max_length=20)
    phone = models.CharField(max_length=15)
    email = models.EmailField()

and a model called Activity, which tracks throught a ForeignKey field the activities registered to a Person 还有一个称为“活动”的模型,该模型在ForeignKey字段中跟踪注册到个人的活动

I need to validate if a Person have not made any activity in 45 days so I can delete her from the database 我需要验证某个人是否在45天内没有进行任何活动,以便可以从数据库中删除她

I thought that a Celery PeriodicTasks could be a solution, but this tasks would have to run every day and query every person in the database to make the validation. 我以为Celery PeriodicTasks可能是一个解决方案,但是该任务必须每天运行并查询数据库中的每个人以进行验证。

Is there a way to create an specific scheduled tasks for every Person instance that runs in 45 days after the instance is saved in the database for the first time? 有没有一种方法可以在实例第一次保存在数据库中后的45天内为每个Person实例创建特定的计划任务?

You can try the following: 您可以尝试以下方法:

1) Add a field 'last_activity' to your model which automatically updates the timestamp of the last activity day of the user. 1)在模型中添加一个字段“ last_activity”,该字段会自动更新用户上次活动日的时间戳。

2) Now create a task which will run after 45 days of the first instance. 2)现在创建一个任务,该任务将在第一个实例的45天后运行。 It will check for all the users whether the timestamp of last_activity_day is 45 days older or not. 它将检查所有用户的last_activity_day时间戳是否早于45天。 If it is, then it will delete the user. 如果是,那么它将删除用户。

But its only the first 45 days you can save the processing for. 但是只有您可以保存处理的前45天。 After that you need to run the task everyday ie, on 46th day, 47th day, 48th day and so on to detect those users whose last_activity was on day 2, day 3 and so on. 之后,您需要每天(即在第46天,第47天,第48天等)运行任务,以检测last_activity在第2天,第3天等等的那些用户。

Hence its better to run a daily task as you yourself mentioned. 因此,最好像您自己提到的那样执行日常任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM