Running a PHP script every 5 minutes and avoiding race conditions

后端 未结 5 1321
无人及你
无人及你 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:33

    If you cannot do what @Brandon suggested, I would recommend the approaching this in the same way I did when writing a daemon in PHP (not the best solution but I was practically forced to do this).

    In my case as well the script accessed a (log)file and did processing on it, afterwards inserting the results in the database. So to ensure that I don't have two files running at the same time, I created a "status" file on which the script acquired a lock and if not able to do so if failed gracefully.

    $fh = fopen('status_file', 'w');
    
    /**
     * LOCK_NB is required because otherwise your script would stall until
     * a lock is aquired, queing a bunch of scripts.
     */
    if(!flock($fh, LOCK_EX | LOCK_NB)) {
      exit 1; // our job is done here
    }
    

提交回复
热议问题