Email Results of Cronjob
I sync various data from twitter, brightkite and flickr into my blog. I use cronjob to achieve this. It is important for me to know if my cron’s are running fine. In my case, I had to tough time getting a cron running. The first problem I encountered was to get DJANGO_SETTINGS_MODULE set. This variable is the key for a django module to execute. I saw that most of the scripts on the web set DJANGO_SETTINGS_MODULE in the cron tab. But it didn’t work for me. So I created a seperate python file(sync.py) with DJANGO_SETTINGS and imported all the models into it. I could access the models as objects and executed the sync functions on those objects which was fairly easy. After getting the cron runningm it is important for me to know if they are working fine. Particularly the twitter API is down for most of the time. Hence I need an email script which could email me the cron results. With great support from webfaction and patrickbeeson I could get one.
This is how you need to get started.
1 * * * * /usr/bin/python /home/yashh/webapps/django /myproject/apps/aggregator/bin/update_feeds.py > /home/yashh/cron.log 2> /home/yashh/cronresults.txt; /usr/local/bin/python2.5 /home/yashh/bin/ email_script.py /home/yashh/cronresults.txt
So the cron script here executes the update_feeds.py file every 1st of an hour. and puts the output into cron.log which inturn is put into another file cronresults.txt. We made the txt file, so that python could read its content and mail us the content. In the next line I simple execute the email_script.py which mails me the cronresults.txt
The email_script.py would like something like this.
#usr/local/bin/python2.5 import sys import smtplib server = smtplib.SMTP('smtpX.webfaction.com') server.login('user_name', 'password') msg = ( "To: firstname.lastname@example.org\r\n" "From: email@example.com\r\n" "Subject: Cron job results\r\n" "Content-type: text/plain\r\n" "\r\n" "%s" ) % open(sys.argv).read() server.sendmail('firstname.lastname@example.org', 'email@example.com', msg) server.quit()
Make sure there are the right permissions on the files. You can also use libgmail for this. You need to modify the email script accordingly. May be this can help you write one. I welcome your views on this issue.