Reputation: 11
sorry if this question has been asked before, however I could not find anything relevant when searching.
I currently have a PHP script which polls a database for the next record which is has not been updated. My question is this: If I then update the database to show that the record is processing while the cron job is running (which takes approx 30 seconds), and the cron job is set to run every second, at second 1 the cron job runs, but will this job wait to complete before the cron job runs for the second time, or will it run at second 2?
Thanks
Upvotes: 1
Views: 5216
Reputation: 305
Use sockets to lock something. Because if script gets terminated, the socket port is automatically open again.
<?php
$port = 1080; // choose unused port
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$sock) {
exit;
}
socket_set_nonblock($sock);
if (!socket_bind($sock, "127.0.0.1", $port)) {
exit;
}
while(1) { ... }
?>
Use a different port per script.
Add this script to Crontab with * * * * *
Upvotes: 1
Reputation: 1816
The cronjob will not wait for the previous one to finish before launching a new instance. What you want is a daemon, see Run php script as daemon process
Upvotes: 0
Reputation:
If you are using cronjob and not using any kind of locking in your php script the cron will run more than one copy of the script if the time event occurs before the last script finished.
To avoid such issue you can do something like this:
$LOCK_FN = "/tmp/my-script.lock"
if(file_exists ($LOCK_FN)){
//previous script is not finish exit.
die("Previous script is not finished yet.");
}
//Create lock
$fp = fopen($LOCK_FN,"w");
fclose($fp);
/*
Put your script logic here
*/
//Open the lock work is done.
unlink($LOCK_FN)
Upvotes: 1