I am working with Heroku lately and am really enjoying the ease of deploying a Django application with it. However, as I am in early development of my app, I don’t really have visitors yet. I noticed that I would take very long to load my website for the first time, while it was fast after that first request. I did some reading and understand that Heroku ‘shuts down’ your server when there is a period of inactivity, when your site doesn’t get visited for a while.
I thought this was rather annoying and definitely not desirable when you try to gain initial visitors — nobody likes to wait ten seconds for a page to load. In this post I’ll show you how I made a workaround that will keep the server alive.
Using Cron and a little Python script
First make a simple python script (e.g. acces_page.py) that loads a URL:
#!/usr/bin/env python import urllib2 if __name__ == '__main__': f = urllib2.urlopen('http://myapp.herokuapp.com') print f.read(10)
Then upload it somewhere on your second – not heroku – server and put it in some folder (e.g. /your/folder/). Then add the following line to your crontab by doing the
crontab -e command.
*/5 * * * * ~/your/folder/access_page.py > $HOME/cron.log 2>&1
This will run the python script every five minutes, accessing the webpage defined in your python script. To test if it works it will output the first 10 characters of the webpage in the file cron.log in your $HOME directory. When you see it’s working, you can remove the
> $HOME/cron.log 2>&1 part.
If the log file says something like access denied, chmod your access_page.py file with
chmod +x access_page.py.