celery perform regular tasks

Celery addition to perform asynchronous tasks, but also support the implementation of recurring tasks or regular tasks. Celery Beat process by reading the contents of the configuration file is periodically sent to the timing task task queue.
Let's look at an example, the project is structured as follows:
__init__.py code is as follows:

[Python]  plain text view  Copy the code
?
1
2
3
from celery import Celery
app = Celery( 'demo' )
app.config_from_object( 'celery_app.celeryconfig' )



celeryconfig.py code is as follows:

[Python]  plain text view  Copy the code
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
from datetime import timedelta
from celery.schedules import crontab
# Broker and Backend
BROKER_URL = 'redis://127.0.0.1:6379'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'
# Timezone
CELERY_TIMEZONE = 'Asia/Shanghai'    # 指定时区,不指定默认为 'UTC'
# CELERY_TIMEZONE='UTC'
# import
CELERY_IMPORTS = (
     'celery_app.task1' ,
     'celery_app.task2'
)
# schedules
CELERYBEAT_SCHEDULE = {
     'add-every-30-seconds' : {
          'task' : 'celery_app.task1.add' ,
          'schedule' : timedelta(seconds = 30 ),       # 每 30 秒执行一次
          'args' : ( 5 , 8 )                           # 任务函数参数
     }
}



task1.py code is as follows:

[Python]  plain text view  Copy the code
?
01
02
03
04
05
06
07
08
09
10
11
12
import time
from celery_app import app
@app .task
def add(x, y):
     time.sleep( 2 )
     return x + y
[mw_shl_code = python,true] import time
from celery_app import app
@app .task
def add(x, y):
     time.sleep( 2 )
     return x + y

[/ mw_shl_code]
Now, let us start the process Celery Worker, execute the following command in the root directory of the project:
celery_demo $ Celery -A celery_app worker --loglevel = info

then start Celery Beat the process, the timing to send the task to the Broker, in execute the following commands in the project root directory:
celery_demo $ Celery Beat -A celery_app
Celery Beat v4.0.1 (latentcall) IS Starting.
__ - __ ... - _
LocalTime -> 2016-12-11 09:48:16
the Configuration ->
    . Broker -> Redis: //127.0.0.1: 6379 //
    . Loader -> celery.loaders.app.AppLoader
    . Scheduler -> celery.beat.PersistentScheduler
    . db -> celerybeat-Schedule
    . logfile -> [stderr] @ the WARNING%
    maxinterval -.> 5.00 minutes (300S)

after the Worker window we can see that the task is performed once every 30 seconds task1
In the above, we use two commands to start the process Worker and Beat the process, we can also put them in a command

$ celery -B -A celery_app worker --loglevel = info

More technical information may concern: gzitcast

Guess you like

Origin www.cnblogs.com/heimaguangzhou/p/11585513.html