Keeping Cron job from eating itself


Forum: Programming and Scripting
Topic: Keeping Cron job from eating itself
started by: jerekeib

Posted by jerekeib on Oct. 27 2006,01:23
I have a cron job that runs a shell script every 2 minutes that wgets several files and compiles an image via imagemagik.

This job normally takes about 30 seconds, but once in a great while it takes longer than the 2 minutes (due to internet congestion or far end server problems) and thus cron starts a duplicate script. Things get worse from there and usually x aborts and I have to restart.

How do I keep cron from executing the script in the event the last one hasn't finished?

Thanks for any light you can shed in this!

Posted by mikshaw on Oct. 27 2006,03:10
I wouldn't bother with cron for something done that frequently.
If you want a 2 minute pause every time, you could put your commands in a function, with the last 2 commands of that function be a 2-minute sleep and then a call to itself.

There's probably a better way, but that at least would prevent overlapping.

Posted by lstark on Oct. 27 2006,04:06
I would edit your script so that it checks to see if an instance of itself is already running.  [Personally I'd do this by 'grep'ing and 'awk'ing the process list for your processes PID.  If it returns a number its running, otherwise it isn't running.  Then with the added info of the PID you can choose to kill the currently running instance if you think its taking too long].   Otherwise if your script is already running, just exit out of the script (or take some other alternative measure besides executing the wget and/or whatever else it does).
Posted by lstark on Oct. 27 2006,04:16
just realized i said something stupid.  If you check the process list you will always have at least one instance of your script running since the script has to be active to be doing the check.

Therefore, count the number of lines that are returned.  1 line means only this instance of the script is running, >1 line means there are other instances already running.

Posted by mikshaw on Oct. 27 2006,04:18
Another possibility....
Check for a particular pid file name, which would rid you of the need to grep and awk the process list.  If the pid file exists, exit.  If the file does not exist, create the file, do your business, remove the file, and exit.

It doesn't even need to be a pid file.  Any uniquely named temp file would work.

Posted by jerekeib on Oct. 27 2006,21:13
Thanks much, I will give that a try and let you know how it goes.

You guys are great!

Powered by Ikonboard 3.1.2a
Ikonboard © 2001 Jarvis Entertainment Group, Inc.