Django中使用Celery执行定时任务问题
作者:G_scsd
这篇文章主要介绍了Django中使用Celery执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
使用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('一生所爱')
2. 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))
3. 启动
先启动项目,然后分别执行下面两个命令
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 启动后的视图

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
