webnoob
webnoob

Reputation: 15934

Issue with flock when running script in cron job

I am using the following code:

$fp = fopen("lock.txt", "w");
if (flock($fp, LOCK_EX|LOCK_NB)) { // do an exclusive lock
    //Do something here.
}else{
   echo "Could not lock file!";
}

This code runs fine when I run my script from my browser (it locks and I can only run it once) but when running it via cron job, the lock.txt file isn't even created. I am a little stumped as I presume the Cron runs as the same user that runs the browser version so it obviously has permissions.

Anyone else had something like this?

EDIT: Ok the file is created now I have done specific paths to the directory. However, the file is overwritten everytime the cron starts an isn't actually locking the file.

Upvotes: 1

Views: 1606

Answers (2)

josh
josh

Reputation: 11

why not use fwrite to overwrite the lock file contents with time() and when your script is finished clear the file.

you can check if the script is running and for how long.

Upvotes: 1

Rakesh Sankar
Rakesh Sankar

Reputation: 9415

This is the correct way to do that.

<?php
$tempDir = sys_get_temp_dir() . "/";
$fp = fopen("$tempDirlock.txt", "r+");

if (flock($fp, LOCK_EX | LOCK_NB)) { // do an exclusive lock
    // do the work

    flock($fp, LOCK_UN); // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);
?>

Upvotes: 4

Related Questions