-1

how i can blocked duplicate script? For example... I have cron every 3 minutes (*/3) and sometime server has slow response and script going duplicate.

*For example i have:*
SELECT id FROM table WHERE partner_id=15
if not exists, create record

But if script going duplicate, i have two inserts with partner_id=15.

What is best practice for lock script for secondary use?

1 Answers1

0

Most simple way is to use a file lock. Lock some file when script if started and release the lock at the end. If the lock cannot be obtained, then another script is running:

<?php

  define("LOCK_FILE_NAME", dirname(__FILE__) . DIRECTORY_SEPARATOR . "lock.lck"); // path and filename of the lock file

  $flockfile = fopen(LOCK_FILE_NAME, 'c');
  if (!flock($flockfile, LOCK_EX | LOCK_NB)) { // try to lock file exclusive, without blocking
    fclose($flockfile); // If no luck - exist
    $flockfile = NULL;
    die('Another process is running');
  }

  print("Lock obtained" . PHP_EOL);

  register_shutdown_function(
    function() use (&$flockfile) {
      if (isset($flockfile)) {
        flock($flockfile, LOCK_UN);  // Release the lock on shutdown
        fclose($flockfile);
        $flockfile = NULL;
        print("Lock released" . PHP_EOL);
      }
    }
  );

  sleep(5); // Emulate some work
AterLux
  • 4,566
  • 2
  • 10
  • 13