gpt4 book ai didi

python - 无法使用 Celery 安排和重新安排帖子

转载 作者:行者123 更新时间:2023-12-04 14:42:50 25 4
gpt4 key购买 nike

我正在开发 Django 博客,我需要能够安排帖子在以后发布。 Celery 非常适合最初安排帖子,但当用户尝试更新帖子以重新安排或无限期取消时,我遇到了问题。

这是我正在尝试做的事情:

def save(self, **kwargs):
'''
Saves an event. If the event is currently scheduled to publish,
sets a celery task to publish the event at the selected time.
If there is an existing scheduled task,cancel it and reschedule it
if necessary.
'''
import celery
this_task_id = 'publish-post-%s' % self.id
celery.task.control.revoke(task_id=this_task_id)

if self.status == self.STATUS_SCHEDULED:
from blog import tasks
tasks.publish_post.apply_async(args=[self.id], eta=self.date_published,
task_id=this_task_id)
else:
self.date_published = datetime.now()

super(Post, self).save(**kwargs)

问题是,一旦 Celery 任务 ID 被列为已撤销,即使在我尝试重新安排它之后它仍然处于撤销状态。这似乎是一项很常见的任务,应该有一个简单的解决方案。

最佳答案

我不知道您的 tasks.py 文件是什么样的,但我认为它类似于以下内容:

from celery.decorators import task

@task
def publish_post(post_id):
''' Sets the status of a post to Published '''
from blog.models import Post

Post.objects.filter(pk=post_id).update(status=Post.STATUS_PUBLISHED)

您应该在任务中编辑过滤器以确保当前状态为 STATUS_SCHEDULED 并且 date_published 中的时间已经过去。例如:

from celery.decorators import task

@task
def publish_post(post_id):
''' Sets the status of a post to Published '''
from blog.models import Post
from datetime import datetime

Post.objects.filter(
pk=post_id,
date_published__lte=datetime.now(),
status=Post.STATUS_SCHEDULED
).update(status=Post.STATUS_PUBLISHED)

这样,用户可以来回更改状态,更改时间,如果任务在 date_published 列之后运行,任务只会将状态更改为发布。无需跟踪 ID 或撤销任务。

关于python - 无法使用 Celery 安排和重新安排帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4510355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com