In my system, I've scheduled a PHP job to run each minute.
Now I want that if 1 instance of this job is running and it takes more than 1 min, the new instance that starts after every minute checks if any previous instance is working and there is any previous instance running, the new one kills itself...I was trying the system(开发者_JAVA技巧) commands but cant figure it out.
Any sugestions
Use exclusive file lock on a lock file. As soon as process ends it execution, the lock is automatically released.
<?php
$fp = fopen("/var/tmp/your.lock", "w");
if (!flock($fp, LOCK_EX|LOCK_NB)) { // try to get exclusive lock, non-blocking
die("Another instance is running");
}
[... continue with the script ...]
See: http://www.php.net/manual/en/function.flock.php
There are several solutions. The thing that is common to all is setting a flag when a job starts, clearing the flag when the job completes. And checking for the existence of that flag when the job starts.
In pseudo code:
if ( flag is set )
exit
set flag
do some stuff
clear flag
You can create a file as your flag for instance. Or you could create a key in memcache and use that as your flag. Or a database, or something else.
精彩评论