How can I ensure I have only one instance of a PHP script running via Apache?

前端 未结 3 1604
暗喜
暗喜 2020-12-14 04:40

I have an index.php script that I use as a post-commit URL on a Google Code site. This script clones a directory and builds a project that may take some work.

相关标签:
3条回答
  • 2020-12-14 05:03

    how long does it take to run.

    could use memcache

    <?php
    $m = new Memcache(); // check the constructor call
    
    if( $m->get( 'job_running' ) ) exit;
    
    else $m->set( 'job_running', true );
    
    
    
    //index code here
    
    //at the end of the script
    
    $m->delete( 'job_running' );
    
    ?>
    

    If the task fails you will need to clear from memcache. Flock is a good option too... probably better actually.

    0 讨论(0)
  • 2020-12-14 05:07

    Only if you save the state of the running script and check when the script starts if an other script is currently active.

    For example to save if a script is running you could do something like this:

    $state = file_get_contents('state.txt');
    
    if (!$state) {
       file_put_contents('state.txt', 'RUNNING, started at '.time());
    
       // Do your stuff here...
    
       // When your stuff is finished, empty file
       file_put_contents('state.txt', '');
    }
    
    0 讨论(0)
  • 2020-12-14 05:16

    You can use flock with LOCK_EX to gain an exclusive lock on a file.

    E.g.:

    <?php
    $fp = fopen('/tmp/php-commit.lock', 'r+');
    if (!flock($fp, LOCK_EX | LOCK_NB)) {
        exit;
    }
    
    // ... do stuff
    
    fclose($fp);
    ?>
    

    For PHP versions after 5.3.2 you need to manually release the lock using flock($fp, LOCK_UN);

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