Search code examples
djangodjango-timezone

check if scheduled actions are due


I use huey to create scheduled tasks, that run for example every minute. I created an example to display my question:

class Campaign(models.Model):
    active              = models.BooleanField("active", default = True)
    name                = models.CharField("campaign name", max_length = 32)

class CampaignTime(models.Model):
    campaign            = models.ForeignKey(Campaign, on_delete = models.CASCADE)
    time_start          = models.TimeField("start time")
    time_end            = models.TimeField("end time")
    running             = models.BooleanField("campaign running right now", default = False)
    ad_to_show          = models.ForeignKey(Ad, on_delete = models.CASCADE)

I am not sure if I implemented this "smoothly":

from django.utils.timezone import localtime as T

class CampaignService:
    for campaign in Campaign.objects.all():
        for ctime in campaign.campaigntime_set.values():
            if T.time() > ctime["time_start"] and ctime["running"] == False:
                ... ## start campaign and set ctime["runnning]" = True
            elif T.time() > ctime["time_end"] and ctime["running"] == True:    
                ... ## end campaign and set ctime["running"] = False
            else:
                continue

This somehow looks crude to me. Any suggestions on how to implement this more nicely?


Solution

  • You can filter with:

    to_start = CampaignTime.objects.filter(
        running=False,
        time_start__lt=T.time(),
        time_end__gt=T.time()
    )
    
    # trigger campaigns of to_start
    to_start.update(running=True)  # set running=True for all to_start objects
    
    to_stop = CampaignTime.objects.filter(
        running=True,
        time_end__lt=T.time()
    )
    
    # trigger campaigns of to_stop
    to_stop.update(running=False)  # set running=False for all to_stop objects