这Django中使用Celery执行异步任务里是引用
这个是接上一个异步任务的代码
定时任务
1. tasks.py中新增两个定时方法
# 定时任务1
@celery_app.task()
def my_crontab(x, y):
print(x, y)
print(f'x 和 y 相加 = {x+y}')
return x + y
# 定时任务2
@celery_app.task()
def my_print():
print('一生所爱')
3. celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoFunction.settings')
app = Celery('test_celery') # 定义全局的Celery任务 test_celery 随便写
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY') # 固定配置
# Load task modules from all registered Django app configs.
app.autodiscover_tasks(['CeleryFunc']) # 把需要用定时任务的APP加进去
from datetime import timedelta
# 新增的定时方法案列
# sum-task 名字任意取
app.conf.update(
CELERYBEAT_SCHEDULE={
'sum-task': {
'task': 'CeleryFunc.tasks.my_crontab',
'schedule': timedelta(seconds=5),
'args': (5, 6)
},
'sum-task1': {
'task': 'CeleryFunc.tasks.my_print',
'schedule': timedelta(seconds=3),
'args': ()
},
}
)
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
4. 启动
先启动项目,然后分别执行下面两个命令
celery -A DjangoFunction beat -l info
celery -A DjangoFunction worker -l info -P eventlet
celery -A DjangoFunction beat -l info 启动后的视图
celery -A DjangoFunction worker -l info -P eventlet 启动后的视图