An easy way to prevent overlapping of cron jobs, is using the GET_LOCK function from MySQL. This function has the following definition:
GET_LOCK(name_of_lock, timeout)It tries to get the named lock name_of_lock for timeout seconds. It returns 1 when it gets the lock, 0 if it timed out and NULL when an error occurred. The lock gets released when you call RELEASE_LOCK, closes the connection or call another GET_LOCK (!). This lock is server wide. This means that any code that connects to the same database server and asks for the same lock, has to wait until you have released it.
A PHP example:
$lock = 0;
// The variable $con is a MySQL connection.
// Try to get the lock for 10 seconds.
$query = "SELECT GET_LOCK('my_lock', 10)";
if (($result = $con->query($query))) {
if (($row = $result->fetch_row())) {
$lock = $row[0];
}
}
if ($lock == 0) {
die("Can't get the lock.");
}
// Here we can do our thing.
// If a job is here, and another job is started, it will not get the lock.
// Here we release the lock.
$con->close();
Comments