Windows下Celery安裝與下使用


Windows下Celery安裝與下使用

一、安裝

# 需要先安裝redis,見`https://www.cnblogs.com/coodyz/p/13410502.html`
pip install celery gevent

二、Demo

1. 文件結構

celery_demo
│  celery.py
│  tasks.py
│  __init__.py

celery.py

from celery import Celery

# 若redis設置了密碼,URI應為`redis://:password@127.0.0.1:6379/1`
app = Celery('celery_demo',
             broker='redis:@127.0.0.1:6379/1',
             backend='redis:@127.0.0.1:6379/1',
             include=['celery_demo.tasks'])

app.conf.update(
    result_expires=3600,
)

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

tasks.py

from .celery import app


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


@app.task
def mul(x, y):
    return x * y


@app.task
def xsum(numbers):
    return sum(numbers)

2. 啟動命令

# module為python module名
celery -A <module> worker -l info -P gevent

3. 測試

在celery_demo的父級目錄運行python。

from celery_demo import tasks
res1 = tasks.add.delay(23333, 1111)
res1.get(timeout=1)
# 24444 測試完成

三、推薦Celery教程和Blog

  1. http://allynh.com/blog/flask-asynchronous-background-tasks-with-celery-and-redis/
  2. https://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html

四、Flask-Celery異步任務


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM