celery

1.celery_app.py文件

BACKEND=redis://:[email protected]:6379/11,

BROKER=‘redis://:[email protected]:6379/12’

TIMEZONE=‘Asia/Shanghai’
from celery import Celery

app = Celery('celery_demo',
             broker=BROKER,
             backend=BACKEND,
             include=['path/task1', 'path/task2']
             )
app.conf.timezone = TIMEZONE
app.conf.enable_utc = False

app.conf.task_send_sent_event = True
app.conf.worker_send_task_events = True

if __name__ == '__main__':
    app.worker_main()

# python3 celery.py

# celery -A celery worker -l info
# celery multi start 1 -A celery -l info -c4 --pidfile=tmp/celery_%n.pid -f logs/celery.log
# celery multi restart 1 -A celery -l info -c4 --pidfile=tmp/celery_%n.pid -f logs/celery.log
# celery multi stop 1 -A celery -l info -c4 --pidfile=tmp/celery_%n.pid

 

2. path/task1.py, task2.py 同task1.py

from celery import app

import time

@app.task

def task1_test(res)

    print('start task1........')

    time.sleep(30)

    print('end task1 -------------')

    return "task1 ------%s" % res

 3.启动celery

命令: python3 celery.py

或者 celery -A celery worker -l info

4. 发送任务

import datetime
ctime = datetime.datetime.now()
utc_tim = datetime.datetime.utcfromtimestamp(ctime.timestamp())
time_delay = datetime.timedelta(seconds=100)
task_time = utc_tim + time_delay

from ... import task1_test
print(datetime.datetime.now())
print(task_time)
result1 = task1_test.delay(('任务1执行'))
print(result1.id)

# eta指定执行时间

result2 = task1_test.apply_async(args=["test1"], eta=task_time)

print(result2.id)

4.获取结果

from celery.result import AsyncResult
from mycelery.celery_app import app

async = AsyncResult(id="e4a07558-868f-40d3-878a-8bc811d9ce1c", app=app)

if async.successful():
    result = async.get()
    print(result)
elif async.failed():
    print('执行失败')
elif async.status == 'PENDING':
    print(async.get())
    print('任务等待中被执行')
elif async.status == 'RETRY':
    print('重试')
elif async.status == 'STARTED':
    print('任务开始被执行')

 

你可能感兴趣的:(celery,python)