Search code examples
djangocelerydjango-celerycelerybeatdjcelery

Any way to make @periodic_task run on call only,it runs automatically on project starts?


Is there any way to make periodic_task to run on call only, I see Pingit() starts as soon as i run my django-app python manage.py runserver

@periodic_task(run_every=crontab(minute="*/1"),options={"task_id":task_name})
    def Pingit():
        print('Every Minute Im Called')

I Would like to make it run the periodic task only if i call it by Pingit.


Solution

  • You may be better to use a @task for this and get it to re-queue itself after it executes, for example:

    @app.task
    def pingit(count=0):
        if count < 60 * 24 * 7:  # 7 days in minutes
            print('Every Minute Im Called')
    
            # Queue a new task to run in 1 minute
            pingit.apply_async(kwargs={'count': count + 1}, countdown=60)
    
    # Start the task manually
    pingit.apply_async()
    

    If you need to add positional arguments to the function, you can specify those with args. For example, to pass a name argument:

    @app.task
    def pingit(name, count=0):
        if count < 60 * 24 * 7:  # 7 days in minutes
            print('Every Minute Im Called')
    
            # Queue a new task to run in 1 minute
            pingit.apply_async(args=[name], kwargs={'count': count + 1}, countdown=60)
    
    # Start the task manually
    pingit.apply_async(args=['MyName'])