Starting Djano upon Reboot using Cron

Three years ago I wrote about starting services as 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, has it would attempt to load before MySQL was running. This made the cron useless, as always after rebooting I would receive an error email saying it couldn’t connect to the MySQL server, and I would have to login and start the Django Server manually. Yesterday I got sick of it, and decided to hack something that will work properly. So my crontab had the following line:

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

which I changed into:

@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 got started. If so, it would start Django as it did before. On the other hand, if MySQL isn’t running it would just sleep for a second and repeat 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 cronjob, but I would have to login anyway to see what wrong with the 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 start/post-start state).

3 thoughts on “Starting Djano 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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.