I've got a bunch of php scripts scheduled to run every couple of minutes in cron on a CentOS machine. I would like for every script to self check if the previous instance of it is still running when it starts and stop if it is.
You can add to your PHP script a simple echo at the end (maybe with date()) which will be visible in your cron logs and shows you if the script reaches the end (and then finish its task)
I do this to manage tasks and making sure they only run one at a time
public function startTask($taskname)
{
$running = "running";
$lockfile = $taskname . "RUNNING";
file_put_contents($lockfile, $running);
}
public function endTask($taskname)
{
$lockfile = $taskname . "RUNNING";
unlink($lockfile);
}
public function isTaskRunning($taskname)
{
$lockfile = $taskname . "RUNNING";
if (file_exists($lockfile))
{
return true;
}
}
You call startTask('name')
when you start the task and then endTask('name')
when you finish. And on the first line of the task you use
if (isTaskRunning('name')) {
die('already running');
}
Put these in a config class or something thats included in all task files and your away
Use a lock file:
<?php
$lockfile = "/tmp/lock.txt";
$fp = fopen($lockfile, "r+");
if (flock($fp, LOCK_EX)) { // acquire an exclusive lock
ftruncate($fp, 0); // truncate file
fwrite($fp, sprintf("Started: %s
PID: %s", date(), getmypid()));
// perform your tasks here.
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!
Check $lockfile for more info.";
}
fclose($fp);
Alternatively, if you are using a database you can do a database Named Lock
like this:
<?php
$process = "myProcess";
$sql = mysql_query("select get_lock('$process', 0)");
$got_lock = (bool)mysql_fetch_array($sql)[0];
// If process is already running exit
if(!$got_lock){
echo "Process running";
exit;
}
// Run my process
for($i=0;$i<100000000;$i++){
echo $i;
}
// Release the lock
mysql_query("select release_lock('$process')");
This form of locking is called a named lock
, it doesn't "Lock" the database, it just creates a "Named Lock" and when you call it it checks to see if the name exists. It is nothing like a table lock
or row lock
It was built into mysql for other applications, such as this.
You can have as many locks as you need, and they are automatically released once the application ends, such as your client disconnecting from mysql: process finishes, php breaks/crashes, mysql crashes (not 100% sure on this one), etc.
http://www.electrictoolbox.com/check-php-script-already-running/ hope this link would be helpful.