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.
This time I will show you how to prevent sleep on the Django side
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
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.