PHP loop acting as cronjob[ensure only one instance running]

后端 未结 2 762
一向
一向 2020-12-18 14:12

I have a multi part question for a php script file. I am creating this file that updates the database every second. There is no other modeling method, it has to be done ever

相关标签:
2条回答
  • 2020-12-18 14:44

    The simplest way to ensure only one copy of your script is running is to use flock() to obtain a file lock. For example:

    <?php
    
    $fp = fopen("/tmp/lock.txt", "r+");
    
    if (flock($fp, LOCK_EX)) { // do an exclusive lock
        ftruncate($fp, 0); // truncate file
        fwrite($fp, "Write something here\n");
        flock($fp, LOCK_UN); // release the lock
    } else {
        echo "Couldn't get the lock!";
    }
    
    fclose($fp);
    
    ?>
    

    So basically you'd have a dummy file set up where your script, upon starting, tries to acquire a lock. If it succeeds, it runs. If not, it exits. That way only one copy of your script can be running at a time.

    Note: flock() is what is called an advisory locking method, meaning it only works if you use it. So this will stop your own script from being run multiple times but won't do anything about any other scripts, which sounds fine in your situation.

    0 讨论(0)
  • 2020-12-18 14:54

    You can't always rely on the lock within the script itself, as stated in the comment to previous answer. This might be a solution.

    #Mins  Hours  Days   Months  Day of week
      *     *      *      *       *   lockfile -r 0 /tmp/the.lock; php parse_tweets.php; rm -f /tmp/the.lock
      *     *      *      *       *   lockfile -r 0 /tmp/the.lock; php php get_tweets.php; rm -f /tmp/the.lock
    

    This way even if the scripts crashes, the lockfile will be released. Taken from here: https://unix.stackexchange.com/a/158459

    0 讨论(0)
提交回复
热议问题