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

安装

1、windows安装地址:  https://github.com/MicrosoftArchive/redis/releases

2、redis windows 版本的安装与使用:https://www.cnblogs.com/qiantao/p/12701199.html

3、redis启动出错Creating Server TCP listening socket *:6379: bind: No error

参见:https://blog.csdn.net/shendixiaoxuan/article/details/78016203

4、window 需要pip install eventlet       https://blog.csdn.net/qq_24077201/article/details/112847331

参考

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
posted @ 2019-12-15 22:55  东方不败--Never  阅读(739)  评论(1编辑  收藏  举报