简体   繁体   中英

Celery periodic task not periodic

I tried to create a task that should run every minute in celery along with redis server

To execute redis I ran "redis-server"

To execute celery I ran "celery -A tasks worker --loglevel=info"

This is my tasks.py file

from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task

app = Celery('tasks', backend='redis://localhost', broker='redis://localhost')


@app.task
def add(x, y):
    return x + y

@periodic_task(run_every=(crontab(minute='1')),name="run_every_minute",ignore_result=True)
def run_every_minute():
    print("hehe")
    return "ok"

When I ran in python console

from tasks.py import run_every_minute
z=run_every_minute.delay()

I got output at celery running terminal as

[2019-06-05 01:35:02,591: INFO/MainProcess] Received task: run_every_minute[06498b4b-1d13-45af-b91c-fb10476e0aa3]
[2019-06-05 01:35:02,595: WARNING/Worker-2] hehe 
[2019-06-05 01:35:02,599: INFO/MainProcess] Task run_every_minute[06498b4b-1d13-45af-b91c-fb10476e0aa3] succeeded in
    0.004713802001788281s: 'ok'

But this should execute every minute since its a periodic task. How this can happen. Also, how can we execute a celery task at some specific time say 5:30 GMT(for example).

Ok, based on the commentary

First periodic_task needs the scheduler/beat be started ( Periodic Tasks ), with this the scheduler will send the task depending in the run_every parameter

celery -A tasks beat

Next, if you need to send the beat every minute, you need the crontab be like this

@periodic_task(run_every=(crontab(minute='*')),name="run_every_minute",ignore_result=True)
def run_every_minute():
    print("hehe")
    return "ok"

With minute='*' , it will send the task every minute. minute=1 will send the task at every hour in the minute one

Answering your last comment:

run_every=(crontab(minute='1'))

You have specified 'minute of hour' = 1, so celery beat runs your periodic task every hour at minute '1', eg 00:01, 01:01 and so on.

You should set hour attribute for your crontab, propably as a range

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