英文:
check if scheduled actions are due
问题
我使用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:
... # 启动活动并设置ctime["running"]为True
elif T.time() > ctime["time_end"] and ctime["running"] == True:
... # 结束活动并设置ctime["running"]为False
else:
continue
对我来说,这看起来有点粗糙。有没有关于如何更好地实现这个的建议?
英文:
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?
答案1
得分: 2
你可以使用以下代码进行筛选:
to_start = CampaignTime.objects.filter(
running=False,
time_start__lt=T.time(),
time_end__gt=T.time()
)
# 触发需要启动的广告活动
to_start.update(running=True) # 为所有 to_start 对象设置 running=True
to_stop = CampaignTime.objects.filter(
running=True,
time_end__lt=T.time()
)
# 触发需要停止的广告活动
to_stop.update(running=False) # 为所有 to_stop 对象设置 running=False
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论