John Smith
John Smith

Reputation: 6197

Php, simple locking against all request to have one

I have a big cron (rebuild a cache) which requires to exclude all other request and hold them or stop them. So only one request should be running at one time.

Can this work out?

$f = fopen("lockfile", 'w+');
if (flock($f, LOCK_EX | LOCK_NB))
{
    sleep(10); // doing the work
}
else
{
    echo 'Come back later!';
}

may this work, even for Windows and Linux? No concurrencing threads then?

Upvotes: 2

Views: 71

Answers (1)

drew010
drew010

Reputation: 69957

If it's really necessary to block clients while the cache is rebuilding, avoid the file locks and just create a file during maintenance, have the clients check for it, and delete it when done.

cron.php

<?php
//..
touch('/path/to/lockfile.dat');
//.. do work
unlink('/path/to/lockfile.dat');

other clients

<?php

if (file_exists('/path/to/lockfile.dat')) {
    die('Under maintenance, please check back shortly.');
}

Upvotes: 3

Related Questions