tags:

views:

330

answers:

3
+5  Q: 

Running a Cron Job

If I have a cron job that run every 10 minutes and for some reason this one time it takes 12 minutes to run the job, will cron start another instance of my code while the previous one is still running? if so how can you prevent this on linux?

+8  A: 

Yes, it will.

You should make your program create a .pid file (for example in /var/run/). When it starts, it should check if such file already exists and if so exit.

Which program/script are you running?

MartinodF
I am running a php script to send mail.
Tony Borf
Something like this will do the trick then http://www.dreamincode.net/code/snippet2407.htm
MartinodF
+2  A: 

Actually, just checking if it exists can be misleading. If the first instance dies, it will not delete it. You actually have to check that the content accounts for a running process' PID (ps tool, with grep can help you here).

This simple approach works quite well and is used by common applicatons such as linux X11 and eclipse IDE.

Warning: This is not appropriate if several instances could be run by hand, as it would allow them all to check at the same time that the file does not exist, and each one of them would create it with its own pid, and run. On cron jobs that actually own the application, this is not the case, and there is no need for a more robuts concurrent control (or to use use the File System locking mechanism).

Daniel Ribeiro
Good point :)
MartinodF
+3  A: 

Yes. Cron will fire off a process at the scheduled interval, regardless if a previous one has not completed.

You can touch a file, like stated in another answer, and check for its existence before engaging your process.

Or you could examine the process list to see if an "instance" is already running:

ps -ef | grep *your_script_name* | grep -v grep | wc -l
Naum