django 检查计划的操作是否到期

yhxst69z  于 2023-03-20  发布在  Go
关注(0)|答案(1)|浏览(140)

我用huey创建计划任务,比如每分钟运行一次。我创建了一个例子来展示我的问题:

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)

我不确定我是否“顺利”地实现了这一点:

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

这在我看来有些粗糙,有什么建议可以更好地实现它吗?

nxowjjhe

nxowjjhe1#

您可以使用以下选项进行筛选:

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

相关问题