环境:
Ubuntu 19.10
python 3.6
django 2.1
django-rq 2.2
pip install django-rq
# django-rq配置
RQ_QUEUES = {
'default': {
'HOST': 'localhost',
'PORT': 6379,
'DB': 10,
'PASSWORD': '123456',
'DEFAULT_TIMEOUT': 360,
},
'with-sentinel': {
'SENTINELS': [('localhost', 26736), ('localhost', 26737)],
'MASTER_NAME': 'redismaster',
'DB': 10,
'PASSWORD': '123456',
'SOCKET_TIMEOUT': None,
'CONNECTION_KWARGS': {
'socket_connect_timeout': 0.3
},
},
'high': {
'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/10'), # If you're on Heroku
'DEFAULT_TIMEOUT': 500,
},
'low': {
'HOST': 'localhost',
'PORT': 6379,
'DB': 10,
}
}RQ_EXCEPTION_HANDLERS= []
CACHES = {
"default": {
"BACKEND": "redis_cache.cache.RedisCache", #缓存到redis中
"LOCATION": "192.168.50.156:6379",
"PASSWORD": "123456",
'TIMEOUT': 60,
},
"low": {
"BACKEND": "redis_cache.cache.RedisCache", #缓存到redis中
"LOCATION": "192.168.50.156:6379",
"PASSWORD": "123456",
'TIMEOUT': 60,
},
}
from django.views import View
from filesystemapi.file_views.function.edit_create import EditCreate
import django_rq
from django.http import JsonResponse
class LabelFile(View):
def get(self, request):
EC = EditCreate()
EC.test1()
queue = django_rq.get_queue('low')
rq_id = "job_test_id1"
rq_job = queue.fetch_job(rq_id) #获取任务
if rq_job:
if rq_job.is_finished: #判断任务是否完成
print('meta', rq_job.meta['data'])
return return return JsonResponse(
status=200,
data=u'任务完成'
)
elif rq_job.is_failed: #判断任务是否失败
rq_job.delete() #删除任务
return return JsonResponse(
status=201,
data=u'任务失败'
)
else:
return return return JsonResponse(
status=202,
data=u'未知'
)
#把函数添加入任务队列中,并创建一个job
rq_job = queue.enqueue_call(
func=EC.test,
args=(),
job_id=rq_id,
)
return return JsonResponse(
status=200,
data=data
)
import rq
def test(self):
print('这是第一个test函数')
rq_job = rq.get_current_job()
rq_job.meta['data'] = "aaa"
rq_job.save_meta()
import time
time.sleep(5)
def test1(self):
print('这是第二个test函数')
python manage.py rqworker default