-1

In Django application, how can I periodically (say every 10 seconds) make a request to an API?

Right now I have setup a cron that takes care of making an API call and updating the data, but cron has a minute precision. I want the data to be updated every 10 seconds.

Lokesh Agrawal
  • 4,095
  • 10
  • 38
  • 76

2 Answers2

0

Create a management command that will call your script five times and will make a pause of 10 seconds after each call. Call that management command every minute from cron.

ipaleka
  • 3,382
  • 2
  • 9
  • 30
0

Use the sched module, which implements a general purpose event scheduler.

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc): 
    print "Doing stuff..."
    # do your stuff
    s.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()

EDIT 1 : My answer wasn't enough specific so here is the answer for django.

In views.py :

import sched, time


s = sched.scheduler(time.time, time.sleep)
def do_something(sc): 
    print "Doing stuff..."
    # Call your API HERE
    s.enter(10, 1, do_something, (sc,))
    return your_value or your template

s.enter(10, 1, do_something, (s,))
s.run()

def home(request, sc):
    api_value = do_something(sc)
    return rendertemplate(request, 'template.html', {'api_value': api_value}
veksor
  • 106
  • 6