Django - Catch moment when Celery has finished running a task

I'm running some Celery tasks and I'm trying to get a clear view when a Celery task has been completed, whether it succeeded or failed. I have created a Backlog model:

class Backlog(models.Model):
    """ Class designed to create backlogs. """
    name = models.CharField(max_length=255, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    #Status
    time = models.DateTimeField(blank=True, null=True)
    has_succeeded = models.BooleanField(default=False)

I have created a Test task in tasks.py to see if I could get a result:

@shared_task(name='Test task', bind=True)
def test_task(self):
    task_id = self.request.id
    result = test_task.AsyncResult(task_id)
    print('Task started with id:', task_id)
    add(2, 2)
    print(result.state)
    if result.state == 'SUCCESS':
        print('Task completed successfully')
        response = {
            'state': result.state,
            'status': str(result.info),
            'date': result.date_done,
        }
        Backlog.objects.create(name=f'Success in task {task_id}', description=str(result.info), time=result.date_done,
                               has_succeeded=True)
    elif result.state == 'FAILURE':
        print('Task is still running or failed with status:', result.state)
        response = {
            'state': result.state,
            'status': str(result.info),
            'date': result.date_done,
        }

        Backlog.objects.create(name=f'Error in task {task_id}', description=str(result.info), time=result.date_done,
                               has_succeeded=False)

And I just test with a simple function:

def add(x, y):
    return x + y

I get the following traceback in the worker:

[2023-02-01 18:47:02,580: WARNING/ForkPoolWorker-6] Task is still running or failed with status:
[2023-02-01 18:47:02,582: WARNING/ForkPoolWorker-6]  
[2023-02-01 18:47:02,582: WARNING/ForkPoolWorker-6] STARTED
[2023-02-01 18:47:02,585: INFO/ForkPoolWorker-6] Task Test task[06f71596-3082-4012-8ea8-05a22d57ca89] succeeded in 0.0534969580003235s: None

I can't manage to catch the exact moment where the state becomes SUCCESS since I only get the STARTED state. What am I missing?

Back to Top