JuConte
JuConte

Reputation: 542

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?

enter image description here

Upvotes: 10

Views: 12633

Answers (4)

Iain Shelvington
Iain Shelvington

Reputation: 32244

To run a task at a specific time you can pass the eta parameter to apply_async

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

Upvotes: 10

cagrias
cagrias

Reputation: 1847

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

Upvotes: 1

sachin dubey
sachin dubey

Reputation: 779

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 .

Upvotes: 0

DejanLekic
DejanLekic

Reputation: 19787

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.

Upvotes: 1

Related Questions