Starting Django upon Reboot using Cron

Three years ago I wrote about starting services as a user via cron instead of init.d (specifically Trac). However, this method has a serious downside: it has no support for dependencies. This really bothered me when I used cron to start a Django server, as it would attempt to load before MySQL was running. This made cron useless, as after every reboot I would receive an error email saying it couldn’t connect to the MySQL server, and I would have to log in and start the Django server manually. Yesterday I got sick of it and decided to hack something together that will work properly. So my crontab had the following line:

@reboot python ./manage.py runfcgi ...options...

which I changed to:

@reboot until /sbin/status mysql | grep start/running ; do echo "Mysql isn't running yet...>&2"; sleep 1; done; python ./manage.py runfcgi ...options...

Basically, it loops and checks whether the MySQL service has started. If so, it starts Django as it did before. On the other hand, if MySQL isn’t running, it just sleeps for a second and repeats the check.

A small issue is that if, for some reason, MySQL won’t start at all, it will loop forever. If this happens, it would mean that I’ll have to manually kill that cron job, but I would have to log in anyway to see what’s wrong with MySQL. So while this method can’t support dependencies like init.d does, it does provide a good-enough solution.

Update 2012-11-23: Fixed the crontab line (it would fail when mysql was in the start/post-start state).

3 thoughts on “Starting Django upon Reboot using Cron”

  1. I wasn’t familiar with supervisor – thanks! However, it seems to lack dependency support: e.g. start django only after mysql was started (I saw an open bug regarding that). Do you know if it’s possible to do? The dependency thing is the major issue for me.

Leave a Reply

Your email address will not be published. Required fields are marked *