django-background-tasks icon indicating copy to clipboard operation
django-background-tasks copied to clipboard

Get the Id of Task that is running me

Open daveisagit opened this issue 5 years ago • 3 comments

Having called manage.py process_tasks which will then call the function given in the task, is it possible for that function to somehow get hold of the Task Id that caused its invocation?

daveisagit avatar Feb 20 '20 11:02 daveisagit

I also tried to find a way of getting this, but no luck

marisancans avatar May 08 '20 16:05 marisancans

Make use of the Task model from background_task.models and fetch the inserted Id from the function running it

vkisku avatar May 12 '20 08:05 vkisku

Make use of the Task model from background_task.models and fetch the inserted Id from the function running it

This is not a reliable method when multiple tasks can be executed at the same time. Using something like Task.objects.latest() there is no guarantee that it is the correct task. Because this package uses @background to register tasks, would it be that hard to add the task id in some sort of a static variable? Something like this:

def static_var(varname, value):
    def decorate(func):
        setattr(func, varname, value)
        return func
    return decorate


@static_var("counter", 0)
def foo():
    foo.counter += 1
    print "Counter is %d" % foo.counter

For now i'm using an ugly way to do this. I'm passing a random hash to function as an argument and later on I search the database to find object that has this hash in argument field.

marisancans avatar May 12 '20 09:05 marisancans