Search code examples
djangocelerydjango-celerydjango-celery-beat

DJANGO_CELERY_BEAT access PeriodicTask from shared_task


In my project, I use django celery beat package to execute scheduled tasks. It works well but I have one case that I can't handle.

All the tasks have a PeriodicTack that schedules them.

So the following task:

from celery import shared_task

@shared_task
def foo(**kwargs):
    # Here I can to things like this :
    whatever_method(kwargs["bar"])

Don't know if it is luck but it turns out that kwargs "points" to the kwargs attribute of the PeriodicTask model.

My question is :

  1. How can I access the PeriodicTask instance that made the task run ?
  2. What if I have 2 PeriodicTask that use the same shared_task but with different schedules/parameters, will it find out which one was the source for that particular run ?

Thanks in advance for your help.


Solution

  • Ok I found a way to do this.

    As I said in the comment, making use of @app.task solves my needs.

    I end up with a task like this :

    @app.task(bind=True)
    def foo(self, **kwargs):
        # The information I personally need is in self properties, like so :
        desired_info = self.request.properties
    
        # Do whatever is needed with desired info...
        # Do whatever else ...
    

    Where app is the Celery app as described in the docs.

    The bind=True is, as I understood, necessary to make the task having its own request and thus having access to self with information.