skip to Main Content

Is it possible to have a single instance of a PHP script running a Windows server and no matter how many requests are directed to this script, only one instance of the script can start and run at a time? After the script finishes its execution then it dies and gets started only after a new requests is received. Queueing requests is not necessary because the running script produces results that are stored in users’ accounts so users can access their accounts and see the result even if their individual request failed. However if multiple instances of the same process would be runnign then they would compete for the same database and I/O resources. So to avoid locks on the database and exclusive handles on resources just one instance of the script is sufficient. However running the script in a continuous loop would consume too much server resources, so the script runs only once every two hours or when it is specifically requested by a user.

2

Answers


  1. Chosen as BEST ANSWER

    Here is a solution using a database that provides for advisory locks, although storing a token in the database will do a similar job.

    1. The script checks if an advisory lock is present in the database, and if is then exits.
    2. If the lock is not present then the script places an advisory lock for transaction.
    3. The lock is automatically released when transaction commits or script crashes.
    

  2. Most simple and portable thing is to use a file lock on some predefined file.

    E.g.

    <?php
      $flockfile = fopen('lockfile.lck', 'c'); // Open a file, the file will be closed when the script ends
      if (!flock($flockfile, LOCK_EX | LOCK_NB)) {
        // If cannot lock the file - just exit
        fclose($flockfile);
        die("Another process is running");
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search