Prevent Heroku (free tier) from sleeping with Django

Heroku server sleeps

With Heroku's free tier, if you don't access the server for 30 minutes, the server will sleep. There are several ways to prevent this.

  1. Charge Heroku
  2. Add add-on
  3. Access regularly with Google apps script etc.

This time I will show you how to prevent sleep on the Django side

How it works

The method this time is to access your server regularly in a separate thread when the server starts.

Since the entry point of the Django application is wsgi.py, write the code in wsgi.py so that the periodic processing is executed in another thread. Reference

Implementation

wsgi.py


import os
import threading
import requests
import time

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hoge.settings")

application = get_wsgi_application()

def awake():
    while True:
        try:
            print("Start Awaking")
            requests.get("http://hogefuga.herokuapp.com/")
            print("End")
        except:
            print("error")
        time.sleep(300)

t = threading.Thread(target=awake)
t.start()

This code accesses its own server every 300 seconds (5 minutes). This will prevent the server from sleeping.

Recommended Posts

Prevent Heroku (free tier) from sleeping with Django
Free from hard-coding functions with SymPy
Internationalization with django
Django Heroku Deploy 2