How to make a celery task fail from within the task?

后端 未结 3 974
忘掉有多难
忘掉有多难 2021-02-05 00:37

Under some conditions, I want to make a celery task fail from within that task. I tried the following:

from celery.task import task
from celery import states

@t         


        
3条回答
  •  醉梦人生
    2021-02-05 01:32

    To mark a task as failed without raising an exception, update the task state to FAILURE and then raise an Ignore exception, because returning any value will record the task as successful, an example:

    from celery import Celery, states
    from celery.exceptions import Ignore
    
    app = Celery('tasks', broker='amqp://guest@localhost//')
    
    @app.task(bind=True)
    def run_simulation(self):
        if some_condition:
            # manually update the task state
            self.update_state(
                state = states.FAILURE,
                meta = 'REASON FOR FAILURE'
            )
    
            # ignore the task so no other state is recorded
            raise Ignore()
    

    But the best way is to raise an exception from your task, you can create a custom exception to track these failures:

    class TaskFailure(Exception):
       pass
    

    And raise this exception from your task:

    if some_condition:
        raise TaskFailure('Failure reason')
    

提交回复
热议问题