简体   繁体   中英

Restart PHP script loop if it takes longer than X seconds

I have a php script that performs some actions in less than 10 minutes (when it doesn't freezes).

The problem is that sometimes, for a reason that I don't know (maybe issues connecting to the remote server) it freezes without any error (cursor blinking like if it was still performing) and it needs to be mannually closed and restarted to work again. Many times I only find that it's stucked with some hours delay and thats not good.

I have already tried max_execution_time, but it returns FATAL ERROR wich doesn't allow me to restart it and that's not the idea.

Here is the sample code:

<?php

ini_set('max_execution_time', 1200); 


while (1) {

    include_once 'once.php';
    sleep(5);
    include 'a.php';
    sleep(5);
    include 'b.php';
    sleep(600);

}

I have a PHP script running on our server that is kind of a worker for a couple of critical jobs. I have another script scheduled as a cron job which "keeps an eye" on this one. Here is how the whole thing looks like :

  1. There are 2 scripts worker.php which has a "while (1)" loop so it never dies and a monitor.php which is scheduled to run every 15 minutes
  2. The worker.php writes its pid to a file every time the loop starts (that way pid is always updated) using getmypid()
  3. Every 15 minutes when monitor.php is executed by a cron job it reads the pid from the file and checks if the process is running by either ps or file_exists('/proc/'.$pid) 3.1. If pid is valid (process is running) it does nothing just exits. 3.2. If pid is invalid, it executes the worker.php. I have also added a mail notification here.

So far I have found cron jobs to be most reliable so I went with this solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM