如何使用MySQL中的datetime在Celery中执行任务? [英] How to execute tasks in Celery using datetime from MySQL?

查看:58
本文介绍了如何使用MySQL中的datetime在Celery中执行任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新闻以发布的 datetime 存储在MySQL数据库中.

News are stored in database MySQL with datetime of publication.

任何时候用户都可以使用延迟日期发布功能在表中添加新内容.

Any time user can add a new in the table with delay date publishing.

如何使用Celery来对数据库表进行列表查询,并检查是否该发布数据了?

How to use Celery for listeting database table and check if it is time to publish data?

发布数据负责另一个过程(脚本Python).因此Celery应该根据 datetime 为MySQL表中的每一行调用此脚本.

For publishing data is responsible another process(script Python). So Celery should call this script for each rows in MySQL table according datetime.

如何使用Celery做到这一点?

How to do that using Celery?

我认为用发布的 date id 创建队列的另一种方法,然后直接将来自用户表单的数据添加到此队列中.因此,应该是一个过程(Celery),该过程观察队列以按日期进一步执行任务.

Another way I think to create queue with date and id of publication then directly add data from user form in this queue. Therefore sholud be process(Celery) that observes a queue for further executing tasks by date.

Celery提供了有关定期任务和计划任务的文档,但是没有解释和使用示例.

Celery provides documentation for Periodic tasks and Scheduled tasks, but there is no explanation and example how to use it.

很抱歉,如果这个问题很琐碎,我是Python Celery的新手.

Sorry if question is trivial, I am a newcomer in Python Celery.

推荐答案

您可以通过在 apply_async()上使用参数 eta 执行任务(请参阅 http://docs.celeryproject.org/en/latest/userguide/Calling.html#eta-and-countdown )

you can execute tasks by using paramater eta on apply_async() (refer to http://docs.celeryproject.org/en/latest/userguide/calling.html#eta-and-countdown)

eta参数必须采用日期时间格式,因此它将以精确的毫秒精度运行.

eta parameter must be in datetime format, so it will be run on the exact millisecond precision.

我建议您使用ORM,因此数据库中的datetime数据类型将由ORM:D

I recommend that you use ORM, so the datetime data type from your database will convert automatically by ORM :D

假设我们有一个 Article 模型:

class Article(models.Model):
    title = models.CharField(max_length=100)
    published = models.BooleanField(default=False)
    created_date = models.DateTimeField()

,然后是我们的任务模块:

@app.task(bind=True)
def set_published(*args, **kwargs):
    article = Article.objects.get(id=args[1])
    article.published = True
    article.save()

    print("article %d has been published" % args[1])

保存新文章,并用 ETA +1分钟

Save the new article and call set_published with ETA+1minute

article = Article(title='This is a new article', published=False, created_date=datetime.utcnow())
article.save()

delta = timedelta(minutes=1)
set_published.apply_async(args=(article.id,), eta=article.created_date + delta)

这篇关于如何使用MySQL中的datetime在Celery中执行任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆