How to make PHP run one copy of a script?

Discussion in 'PHP' started by patlatyj, Feb 23, 2008.

  1. #1
    Hello, actually I want to write a demon - a script, working permanently, so I intend to use cron to launch a PHP script every minute and if that script is already running, die. But I don't know how to get informed if the script is running, I don't like the variant with creating and deleting a file, while it will break after an Apache reboot, and I don't think using bash is necessary - all shared hosts don't allow that. I tried to use flock LOCK_EX, but I failed, the actual code is
    $f=fopen('.lockfile','wb') or die('Unable to open lockfile');
    if (!flock($f, LOCK_EX + LOCK_NB)) die('File locked');
    echo 'working with file for a minute';
    sleep (60);
    flock($f, LOCK_UN);
    fclose($f);
    
    Code (markup):
    but the script would run 2 and more copies. Please help me....
     
    patlatyj, Feb 23, 2008 IP
  2. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #2
    Use database with a variable is_done set to 1/0.

    Peace,
     
    Barti1987, Feb 23, 2008 IP
  3. jnestor

    jnestor Peon

    Messages:
    133
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The db method has the same issue. If the program dies it will leave the lock in place and you'll need to manually remove the lock to get it running again.

    The code in the OP works for me as written.
     
    jnestor, Feb 23, 2008 IP
  4. decepti0n

    decepti0n Peon

    Messages:
    519
    Likes Received:
    16
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Maybe I'm not getting the question, but sometimes when I need to make a file 'unavailable' at least, I just rename it, or if it's included in a bunch of other things, just duplicate it, rename the backup something else, then wipe the original one. Then replace it at the end
     
    decepti0n, Feb 23, 2008 IP
  5. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #5
    Easy, add a field with the last_touch timestamp and update it every minute or so.

    Peace,
     
    Barti1987, Feb 23, 2008 IP