【问题标题】:How fix run duplicate PHP script如何修复运行重复的 PHP 脚本
【发布时间】:2021-01-16 23:54:56
【问题描述】:

如何阻止重复的脚本?例如...我每 3 分钟执行一次 cron (*/3),有时服务器响应缓慢,脚本会重复。

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

但如果脚本重复,我有两个插入,partner_id=15。

锁定脚本二次使用的最佳做法是什么?

【问题讨论】:

标签: php import


【解决方案1】:

最简单的方法是使用文件锁。在脚本启动时锁定某些文件,并在最后释放锁定。如果无法获得锁,则另一个脚本正在运行:

<?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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 2011-07-15
    • 1970-01-01
    相关资源
    最近更新 更多