如果确实需要设置任务超时,可以使用子进程来实现,代码如下
import json
from multiprocessing import Process
from celery import current_app
from celery.exceptions import SoftTimeLimitExceeded
soft_time_limit = 60
@current_app.task(name="task_name")
def task_worker(self, *args, **kwargs):
def on_failure():
pass
worker = Process(target=do_working, args=args, kwargs=kwargs, name='worker')
worker.daemon = True
worker.start()
worker.join(soft_time_limit)
while worker.is_alive():
worker.terminate()
raise SoftTimeLimitExceeded
return json.dumps(dict(message="ok"))
def do_working(*args, **kwargs):
pass # do something