boxine / django-huey-monitor

Django based tool for monitoring huey task queue: https://github.com/coleifer/huey
GNU General Public License v3.0
86 stars 20 forks source link

manage.py command to delete old data #130

Open dwjorgeb opened 11 months ago

dwjorgeb commented 11 months ago

In order to allow us do some regular house-cleaning, this extension should have a command to flush old (no longer relevant) task data.

Would be even more helpful if we could specify the number of days to keep, something like:


python3 manage.py huey_monitor_flush 30

would delete task data older than 30 days.

This would be a great addition, as task data, if left unchecked, will start to grow larger and larger.

jwaschkau commented 10 months ago

Implementing this as a management command is pretty simple. Feel free to use or modify following code to your liking.

from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from huey_monitor.models import TaskModel

class Command(BaseCommand):
    help = 'Remove huey tasks older than X days.'  # noqa

    def add_arguments(self, parser):
        parser.add_argument('--days', type=int, default=14)

    def handle(self, *args, **options):
        tasks = TaskModel.objects.filter(
            finished=True,
            create_dt__lt=timezone.now() - timedelta(days=options['days'])
        )
        task_count = tasks.count()
        tasks.delete()
        self.stdout.write(self.style.SUCCESS(f'{task_count} tasks deleted'))