Django 2.2 使用 celery 4.3.0 做异步任务和定时任务

1. 在Django 项目的 settings.py 同级目录创建文件 celery.py

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# 把置默认的django settings模块配置给celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ProjectName.settings')
app = Celery('ProjectName')

# 这里使用字符串以使celery的worker不用为子进程序列化配置对象。
# 命名空间 namespace='CELERY'定义所有与celery相关的配置的键名要以'CELERY_'为前缀。
app.config_from_object('django.conf:settings', namespace='CELERY')

# 从所有django app configs中加载task模块,
# 如果你把所有的task都定义在单独的tasks.py模块中,
# 加上这句话celery会自动发现这些模块中的task,实际上这句话可以省略。
app.autodiscover_tasks()

2. 在 ProjectName 目录下的 __init__.py 文件中添加:

from __future__ import absolute_import, unicode_literals
from ProjectCyclone.celery import app as celery_app

__all__ = ('celery_app',)

3.在settings.py文件中添加配置:

# Celery application definition
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/1'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERYD_MAX_TASKS_PER_CHILD = 10
CELERYD_LOG_FILE = os.path.join(BASE_DIR, "logs", "celery_work.log")
CELERYBEAT_LOG_FILE = os.path.join(BASE_DIR, "logs", "celery_beat.log")

# 这里是定时任务的配置
CELERY_BEAT_SCHEDULE = {
    'task_method': { # 随便起的名字
        'task': 'app.tasks.method_name', # app 下的tasks.py文件中的方法名
        'schedule': timedelta(seconds=10), # 名字为task_method的定时任务, 每10秒执行一次
    },
}

4. 异步任务:在 app 目录下的view.py文件中创建:

from ProjectName.celery import app
@app.task
def test_celery(x, y):
    time.sleep(3)
    return x * y


def test(request):
    k = test_celery.delay(10, 1)
    print(k)
    return HttpResponse("async tasks")

5. 定时任务:在对应的 app 模块的目录下创建 tasks.py 文件:

from __future__ import absolute_import
from celery import shared_task


@shared_task
def something():
    print("haha")
    return "crontab tasks"

启动celery:celery worker -A tasks --loglevel=info

同时启动works 和beat:celery -B -A ProjectName worker --loglevel=info

 

 参照:https://yq.aliyun.com/articles/619930 https://zyqzyq.github.io/2018/06/27/django-+-celery-+-supervisor-%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1-+-%E9%83%A8%E7%BD%B2.html#%E5%AE%89%E8%A3%85django-celery-results

参考:http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#starting-the-scheduler

https://blog.csdn.net/qq_33020901/article/details/70037501

https://blog.csdn.net/Coxhuang/article/details/89058429

https://blog.csdn.net/sjheiya/article/details/83152684#worker_67

https://www.cnblogs.com/linxiyue/p/8082102.html

你可能感兴趣的:(Django 2.2 使用 celery 4.3.0 做异步任务和定时任务)