Easily Schedule Periodic Tasks in Django/Python Using Uptime Robot

django periodic tasks uptime robot

When I setup a new Django project I was looking for an easy way to schedule periodic tasks like crawling an API, removing old entries from a database, or sending an Email. Unfortunately I was not able to find a quick, easy, and straightforward solution. I had a look at cronjobs, Celery, and many more. They did not offer what I wanted.

Because of this, I created an alternative solution using UptimeRobot.com. Here is how it works.

What is Uptime Robot?

Uptime Robot is a monitoring website that lets you setup a monitor on your website. If your website is down for some reasons you will get a notification Email or a text message. I have setup a monitor to https://www.cointimemachine.com/health-check/UptimeRobot.com check it every 5 minutes. You can also set any other value, for example 30 minutes, 1 hour, 5 hours, or 24 hours. If my website is not reachable anymore UptimeRobot will send me an Email.

Using UptimeRobot.com to Schedule Regular Tasks

UptimeRobot.com checks your website in a periodic interval. How about we “hide” some functionality/code on the pages which are triggered by UptimeRobot.com in the interval which was defined by us?

First we will create a regular Django view where our periodic task is defined. You can add any logic in this view. However, keep in mind that the task should not be a long running task, since there will likely be a timeout and UptimeRobot.com will inform you that your website is down.

from django.shortcuts import render
from django.http import HttpResponse

def periodic_task(request):
    return_value = 'Task complete!'
    # put your logic which should be run every XXX minutes here

    # return value if you want
    return HttpResponse(return_value, content_type="text/plain")

Next setup the path/URL to trigger the task. I would recommend to use a long path which contains random values like q7pApNjFx81LfgPKYz7jVEljocDsQirT since you do not want other people to guess the correct path and let them trigger the task manually. You can generate a random string here.

from django.urls import path, re_path, include
from . import views

urlpatterns = [    
    re_path(r'^$', views.home, name='home'),
    re_path(r'^q7pApNjFx81LfgPKYz7jVEljocDsQirT/periodic-task-1/$', views.periodic_task, name='per_task'),
]

Your Django website is now ready. You can trigger the task just by browsing to

localhost:8000/q7pApNjFx81LfgPKYz7jVEljocDsQirT/periodic-task-1/

Since you do not want to trigger the task manually, the next step is to create an account at UptimeRobot.com and setting up your first monitor with the URL as shown above.

That’s it! You created a task scheduler that will periodically “crawl” your website and thus trigger a periodic task without a lot of effort. I hope you like it. Please leave a comment!