简体   繁体   中英

how to start a task at a specific time with django & celery

I'm using Celery, and it works for async, but I need to set up an operation to a specific datetime.

For example "on the 30th of August, 2019, at 11:35, do this."

My celery.py is very simple now, but it works:

import time
from datetime import datetime, timedelta
from datetime import date
from celery import shared_task,current_task, task
from celery import Celery

app = Celery()

@app.task
def test():

    print ('1')
    todaynow = datetime.now()

    print todaynow

I call it from view and run print on rabbit

Any idea for how to program a task?

ty

EDIT:

I try in view to call "test"

test.apply_async(eta=datetime(2019, 7, 31, 6, 28))

in flower it receive the task but not execute it, why?

在此处输入图片说明

Celery component responsible for scheduling tasks to run at specific time, or repeatedly after some time is called the Celery Beat (scheduler). Celery documentation has a complete section describing it, with details how to run it, and how to configure it. If you are familiar with crontab you will easily create your own scheduled task-runs.

To schedule task you need to use celery beat .

from celery.task import periodic_task 
@periodic_task(run_every=crontab(minute="*")) # It will run your task every minute
def schedule_task():
    print('1')
    todaynow = datetime.now()
    print(todaynow)

You can schedule your task at any specific time using periodic task . To know more use this link https://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html .

Don't forget to restart your celery beat after creation of task .

You can create a single executed periodic scheduler for "the 30 of august 2019 at 11 and 35 min do this" by using celery such as:

import time
from datetime import datetime, timedelta
from datetime import date
from celery import Celery, shared_task,current_task, task
from celery.schedules import crontab

app = Celery()

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    sender.add_periodic_task(
        crontab(hour=11, minute=35, day_of_month=30, month_of_year=8),
        test.s(),
        expires=1
    )


@app.task
def test():
    print ('1')
    todaynow = datetime.now()

    print todaynow

要在特定时间运行任务,可以将eta参数传递给apply_async

test.apply_async(eta=datetime.datetime(2019, 8, 30, 11, 35))

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