celery+django+mq 异步任务与定时任务

参考

celery
pip install celery==4.1.1
https://www.cnblogs.com/wdliu/p/9530219.html
https://www.jianshu.com/p/6f8576a37a3e

定时:
https://blog.csdn.net/Leo062701/article/details/90613651
https://blog.csdn.net/sicofield/article/details/50937338

配置

dj_01/dj_01/__init__.py

1 import pymysql
2 from .celery import app as celery_app
3 
4 pymysql.install_as_MySQLdb()
5 __all__ = ['celery_app']

dj_01/dj_01/celery.py

 1 from __future__ import absolute_import, unicode_literals
 2 import os
 3 from celery import Celery
 4 from django.conf import settings
 5 # set the default Django settings module for the 'celery' program.
 6 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dj_01.settings')
 7 
 8 app = Celery('dj_01',backend='amqp', broker='amqp://guest:guest@localhost:5672//')
 9 app.config_from_object('django.conf:settings')
10 app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

dj_01/dj_01/setting.py


INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mytest',

)
1 

# Celery 设置 2 # CELERY_BROKER_URL = 'redis://localhost:6379/0' 3 BROKER_URL = 'amqp://guest:guest@127.0.0.1:5672//' 4 CELERY_ACCEPT_CONTENT = ['json'] 5 CELERY_TASK_SERIALIZER = 'json' 6 CELERY_RESULT_SERIALIZER = 'json' 7 # CELERY_RESULT_BACKEND = 'django-db' 8 CELERY_TIMEZONE = 'Asia/Shanghai' 9 10 from datetime import timedelta 11 12 # 定时任务 13 CELERYBEAT_SCHEDULE = { 14 'add-every-30-seconds': { 15 'task': 'mytest.tasks.add', # 任务名 16 'schedule': timedelta(seconds=2), # 每2s执行一次该任务 17 'args': (2, 3) 18 } 19 }

 

异步任务

服务:celery -A dj_01 worker -l info

app/tasks.py

 1 from time import sleep
 2 from celery import shared_task
 3 
 4 @shared_task  #celery -A dj_01 worker -l info
 5 def celeryTest(*ags,**kwargs):
 6     print('耗时操作任务start...')
 7     print(ags)
 8     print(kwargs)
 9     sleep(10)
10     print('耗时操作任务end...')

app/view.py


from .tasks import celeryTest

1 def testt(req): 2 d = { 3 "result":'123123', 4 } 5 6 res = celeryTest.delay(json.dumps(d)) 7 print("res:%s"%res) #b9020fb2-61c1-494d-8e66-a86776943c76
8     return render(req, 'acc_login.html')

 

定时任务

服务:celery -A dj_01 beat -l info

https://blog.csdn.net/Leo062701/article/details/90613651
https://blog.csdn.net/sicofield/article/details/50937338
上一篇:dijkstra算法:链式前向星+堆优化


下一篇:机器人关节空间轨迹规划--S型速度规划