简体   繁体   中英

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?

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. 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 ?.

  • What about the args . In my case should i pass the value of User and command from args . Or i can simply pass from the task key ?

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 ?

  • 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 .

    Celery will import the task for you, provided that import foobar.execute_command would work.

  • Check the celery.schedule.crontab API ; the following should execute on weekdays at 07:30 am:

     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.

    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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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