Django中——Celery的异步任务和定时任务

一、Celery异步任务

# -----项目初始化文件中设置
# 1、加载Django项目配置
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zufang.settings')

# 2、创建Celery对象,指定模块名、消息代理(消息队列)和持久化方式
app = celery.Celery(
    'zufang', # 
    broker='redis://120.77.222.217:6379/1', # 消息队列
    backend='redis://120.77.222.217:6379/2' # 持久化到
    # broker='amqp://luohao:[email protected]:5672/zufangwang_vhost',
    # backend='django-db' # 持久到mysql数据会有问题需要修改以下问题
	{
		1、pip install django-celery-results
		2、INSTALLED_APPS = ['django_celery_results']
		3、python manage.py migrate django_celery_results
		# 会迁移失败,解决方法如下
		{
			1、删除django_celery_results 和 django_migrations
			2、修改数据库: sql_safe_updates 为 OFF
					show variables like '%safe%'
					set session sql_safe_updates = off;
					set global sql_safe_updates = off;
			3、再次执行迁移:python manage.py migrate django_celery_results
		}
		4、自动从指定的应用中发现任务(异步任务/定时任务)
			app.autodiscover_tasks(('应用', ))
	}
)
# ------ 添加异步任务
QINIU_ACCESS_KEY = 'KarvlHfUdoG1mZNSfDVS5Vh3nae2jUZumTBHK-PR'
QINIU_SECRET_KEY = 'SFPFkAn5NENhdCMqMe9wd_lxGHAeFR5caXxPTtt7'
AUTH = qiniu.Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)

# 封装异步任务
@app.task
def upload_file_to_qiniu(file_path, filename):
	token = AUTH.upload_token(QINIU_BUCKET_NAME, filename)
	return qiniu.put_file(token, filename, file_path)

# 执行异步任务,三种执行方式
{
	1、upload_file_to_qiniu.delay(file_path,filename)
	2、task = upload_file_to_qiniu.s(countdown=延迟做任务,expires=超时取消任务)
		task.delay(file_path,filename)
	3、upload_file_to_qiniu.applay_async((file_path,filename),
				queue='queue1',countdown=10, # 指定消息队列,延迟时间
				retry_policy={'max_reties':3}, # 重试发送次数
				expires = 60,compression='zlib') # 超时时间,压缩方式
				)
}
# 启动生产者
# 启动消费者

二、Celery定时任务

# ---------配置文件
from celery.schedules import crontab
app.conf.update(
			timezone=settings.TIME_ZONE,
			enable_utc=True,
			beat_schedule={
				'task':{  # 任务一
					'task':'common.tasks.display_info', # 指定要执行的---- 函数名
					'schedule':crontab('*','*','*','*','*'), #---- 定时任务调用执行时间
					'args':('hello,world',) # 是display_info参数
					},
				'task2':{}, # 任务二
				})
# ------------ 定义函数
@app.tast
def display_info(conntent):
	print(content)

# 启动生产者和消费者

Celery消息队列监控:

pip install flower
celery flower --broker = amqp://luohao:密码@主机:端口/数据库(指定消息队列)

Celery 原语:

1、任务打包异步执行 -group - 将一组任务异步执行并返回一组结果

		from celery import group
		task_group = group(task1(),task2(),...)
		result = task_group() --- list
		
2、链式执行 -chain- 按顺序链式执行任务并将上一个任务的结果传给下一个任务
		from celery import chain
		task = chain(task1.s()|task2.s()|...)
		result = task()
发布了128 篇原创文章 · 获赞 0 · 访问量 2517

猜你喜欢

转载自blog.csdn.net/qq_41134008/article/details/105088155