Running a PHP script every 5 minutes and avoiding race conditions

后端 未结 5 1309
无人及你
无人及你 2021-01-12 12:13

I have a php script that needs to run once every 5 minutes. Currently I\'m using a cron job to run it (and it works great) but my host only allows a minimum time of 15 minut

5条回答
  •  长发绾君心
    2021-01-12 12:29

    Have you considered just having your script run an infinite loop with a sleep to wait 5 minutes between iterations?

    for (;;)
    {
      perform_actions();
      sleep(300);
    }
    

    Alternatively, you could have a file (for example, is_running), and get an exclusive lock on it at the start of your script which is released at the end. At least this way you will not do anything destructive.

    You could also combine these two solutions.

    $fp = fopen("is_running", "r+");
    
    /* is it already running? */
    if (! flock($fp, LOCK_EX | LOCK_NB)) return;
    
    for (;;)
    {
      perform_actions();
      sleep(300);
    }
    

    And then have the cron job still run every 15 minutes. If the process is still running, it will just bail out, otherwise it will relaunch and resume updating every 5 minutes.

提交回复
热议问题