Reputation: 171
In my models, I care about how long each object has been in the database and flagged as active. so if the model is active for more than a number of days, it should give an alarm icon in every place the name of the object appears.
At the moment I am calculating the dates difference (today - creation date) for all the objects in every GET request. But I don't think it is the right way to do this because I will have thousands of objects when the website is over.
What is the professional way to do such checks? Thank you
Upvotes: 0
Views: 1536
Reputation: 51988
Try using celery periodic task.
Make a Celery Schedule like this:
from celery.schedules import crontab
CELERYBEAT_SCHEDULE = {
'add-every-monday-morning': {
'task': 'tasks.check_active_objects',
'schedule': crontab(minute=0, hour=0), # Will run everyday midnight
},
}
And add this method to tasks.py to make the objects flagged which are created before threshold time:
@app.task
def check_active_objects():
current_time = datetime.now()
threshold_time = current_time - datetime.timedelta(days=2)
YourModel.objects.filter(creation_date__lte = threshold_time).update(alarm_flag=True) # Make a field active for alarm
Upvotes: 1
Reputation: 55448
Let's isolate the function that does the check, that you call on each GET request. Let's name that function run_checks()
What run_checks()
should do is, run on your whole database, or a subset of it, e.g. from date X to date Y, depending on your business. The other thing it should do if possible: it should persist the state of the check. E.g. if you are flagging these with icons, you can have a MyModel.flagged = True/False
or MyModel.flagged = NULL/date
.
Persisting the state of the report allows you to take shortcuts in the next run, e.g. where you can run the check only on non-flagged rows, e.g. rows_to_check = MyModel.objects.exclude(flagged=True)
Now once you have that check function:
You can make it into a ./manage.py run_checks
custom Django command and call it periodically from cron (with a @daily command),
Or, schedule it periodically on a task queue (Celery, django-background-task, python-rq, etc)
Upvotes: 1