django-q icon indicating copy to clipboard operation
django-q copied to clipboard

[Bug] Cron - Scheduled task should not execute immediately

Open 1oglop1 opened this issue 3 years ago • 3 comments

When I create a task using django_q.tasks.schedule without calculating the next run it executes the task right away.

django_q.tasks.schedule(
                name=batch_creation_schedule,
                func="tqs.admin.i_am_taskin", 
                n="a value",
                hook="hooks.print_result",
                schedule_type=django_q.models.Schedule.CRON,
                cron="*/10 * * * *",  # every 10 minutes
            )

Assume the following scenario:

The task django_q.tasks.schedule is called at 10:03, expected cron default behaviour for the next run is 10:10 however django-q set's next execution to now which is either 10:03 or 10:04 Subsequent executions are correct though.

See this, for example, https://crontab.guru/#/10_*_

This is a problem because I have the button that is supposed to enable/disable a scheduled task that runs every Monday and I have to recalculate every time when the next Monday is.

1oglop1 avatar Aug 17 '21 11:08 1oglop1

Hi try this

from django.dispatch import receiver
from django_q.tasks import Schedule
from django.db.models.signals import pre_save
from croniter import croniter
from datetime import datetime


@receiver(pre_save, sender=Schedule)
def modify_cron_next_run_time(sender, instance, **kwargs):
    if instance.schedule_type == "C" and instance.cron and instance.pk is None:
        now = datetime.now()
        cron_schedule = instance.cron
        cron = croniter(cron_schedule, now)
        next_run = cron.get_next(datetime)
        instance.next_run = next_run

Ofc later you must import file with this code somewhere to initiate signal

Packman700 avatar Nov 14 '21 12:11 Packman700

Same issue.

lane-eb avatar Jan 24 '24 07:01 lane-eb