简体   繁体   English

如何在Django应用程序中使用celery执行任务?

[英]How to execute a task using celery in Django application?

I posted a question : How to execute a command at exact time once a day in Django? 我发布了一个问题: 如何每天在Django的确切时间执行一次命令?

I got my answer that the Celery is the easiest option to do it, but now i have another question regarding the celery: 我的回答是芹菜是最简单的选择,但是现在我对芹菜还有另一个问题:

from celery.schedules import crontab

CELERYBEAT_SCHEDULE = {
    # Executes every Monday morning at 7:30 A.M
    'every-monday-morning': {
        'task': 'tasks.add',
        'schedule': crontab(hour=7, minute=30, day_of_week=1),
        'args': (16, 16),
    },
}

I have three question in regarding the above code ie: 关于上述代码,我有三个问题:

  • I have to execute execute_command(User, command) method. 我必须执行execute_command(User, command)方法。 I want that this method will execute at the given scheduled time. 我希望此方法将在给定的计划时间执行。

  • What if i want to change the schedule at 7:30 AM but every weekdays ?. 如果我想在7:30 AM but every weekdays更改时间表,该怎么办?

  • What about the args . args In my case should i pass the value of User and command from args . 就我而言,我应该从args传递User and command的值。 Or i can simply pass from the task key ? 或者我可以简单地通过task密钥传递?

I just read the docs of celery, but didn't got my answer. 我只是看了芹菜的文档,但没有得到我的答案。 Would you please help me? 你能帮我吗?

Did you find the Celery periodic tasks documentation ? 您是否找到了Celery定期任务文档

  • You'll have to use the identifier of your method to register a scheduler entry. 您必须使用方法的标识符来注册调度程序条目。 If your execute_command task lives in a module named foobar , the task value of the CELERYBEAT_SCHEDULE structure should be foobar.execute_command . 如果您的execute_command任务位于名为foobar的模块中,则CELERYBEAT_SCHEDULE结构的task值应为foobar.execute_command

    Celery will import the task for you, provided that import foobar.execute_command would work. 只要可以import foobar.execute_command ,Celery就会为您导入任务。

  • Check the celery.schedule.crontab API ; 检查celery.schedule.crontab API the following should execute on weekdays at 07:30 am: 以下代码应在工作日上午07:30执行:

     crontab(minute=30, hour=7, day_of_week='mon-fri') 
  • Remember that this task is going to be performed asynchronously. 请记住,该任务将异步执行。 You cannot query for a database object when you schedule this task and expect it to be there still when the task is called. 在计划此任务时,您无法查询数据库对象,并且在调用该任务时希望它仍然存在。

    Thus, you should only pass in python values that remain constant, and have your task connect to the database and look things up based on the arguments you pass in. 因此,您只应传入保持不变的python值,并使您的任务连接到数据库,并根据传入的参数查找内容。

    If this task is only ever going to execute tasks for one specific user, then by all means pass in the identifier for that user (user id, email, whatever you can use to look up the user from the database). 如果此任务只打算为一个特定用户执行任务,则一定要传递该用户的标识符(用户ID,电子邮件,以及可以用来从数据库中查找用户的任何内容)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM