0

I am trying to learn how to scheduled a task in Django using schedule package. Here is the code I have added to my view. I should mention that I only have one view so I need to run scheduler in my index view.. I know there is a problem in code logic and it only render scheduler and would trap in the loop.. Can you tell me how can I use it?

def job():
    print "this is scheduled job", str(datetime.now())

def index(request):
    schedule.every(10).second.do(job())
    while True:
        schedule.run_pending()
        time.sleep(1)

    objs= objsdb.objects.all()
    template = loader.get_template('objtest/index.html')
    context= { 'objs': objs}
    return HttpResponse(template.render(context, request))
HHH
  • 21
  • 3

1 Answers1

1

You picked the wrong approach. If you want to schedule something that should run periodically you should not do this within a web request. The request never ends, because of the wile loop - and browsers and webservers very much dislike this behavior.

Instead you might want to write a management command that runs on its own and is responsible to call your tasks.

Additionally you might want to read Django - Set Up A Scheduled Job? - they also tell something about other approaches like AMPQ and cron. But those would replace your choice of the schedule module.

dahrens
  • 3,879
  • 1
  • 20
  • 38