1

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.

M.javid
  • 6,387
  • 3
  • 41
  • 56
Arbazz Hussain
  • 1,622
  • 2
  • 15
  • 41
  • Do you mean that `Pingit()` should only be started by a manual call, but once it has been started then it will then run every 1 minute? – Will Keeling Sep 17 '18 at 10:50

1 Answers1

1

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'])
Will Keeling
  • 22,055
  • 4
  • 51
  • 61
  • Creative approach Will, TQ! – Arbazz Hussain Sep 17 '18 at 13:35
  • `[2018-09-17 13:35:00,078: INFO/ForkPoolWorker-3] Task cimexapp.tasks.pingit[6530114a-4262-49fd-ad24-a22773573db0] succeeded in 0.005711002973839641s: None [2018-09-17 13:35:00,081: INFO/MainProcess] Received task: cimexapp.tasks.pingit[9cfbe0c7-7a83-4de0-a0c0-8970330395d2] ETA:[2018-09-17 19:05:10.073313+05:30] [2018-09-17 13:35:10,345: INFO/ForkPoolWorker-3] Task cimexapp.tasks.pingit[9cfbe0c7-7a83-4de0-a0c0-8970330395d2] succeeded in 0.004679549019783735s: None` just wonder why tasks doesn't show "completed" or "successed" status ? – Arbazz Hussain Sep 17 '18 at 13:43
  • > How can we pass arguments to it ? – Arbazz Hussain Sep 17 '18 at 18:16
  • `def domainMonitorSchedule(name,count=0,): print(name) domainMonitorSchedule.apply_async(kwargs={'count': count + 1}, countdown=10)` and calling `domainMonitorSchedule.apply_async('MyNameisXXX')` – Arbazz Hussain Sep 17 '18 at 18:17
  • I updated the answer with an example of how you can pass a `name` argument. Hope that helps. – Will Keeling Sep 17 '18 at 20:17