Home > OS >  echo something only once in infinite loop on php (Laravel)
echo something only once in infinite loop on php (Laravel)

Time:12-10

I have a (Laravel) command. the command is doing curl to a website, it's some kind of site checker. when the server is down I want to echo out something but it should be only once.

tried this code. doesn't work. it keeps echo ing. and now I'm getting stuck.

class Monitoring extends Command {
     protected $signature = 'run:monitoring';

     private $state;

     public function __construct() {
         parent::__construct();
    
         $this->state = false;
     }

     public function handle() {
         while (true) {
            if (!$this->isMyServerAlive()) {
                $this->state = true;

                if ($this->state) {
                    echo 'THE SERVER IS DOWN!!!';
                }
            } else {
                $this->state = false;
            }
        }
         
     }

     private function isMyServerAlive() {
         return false; // let's say the server is down
     }

}

I know the code above will keep echoing.

The goal is when the isMyServerAlive() function returns to true from false and returns to true again, it will be echoing only once for second time, and so on and so forth.

I hope this message is clear.

Any better workaround than this?

CodePudding user response:

You could use a variable which you toggle that will determine whether or not to echo out your message.

Initially you would want it be true so that when your server becomes unavailable it triggers the message. You then set it to false to prevent the message being triggered again until the value is set back to true.

So something like;

private $shouldNotify = true;

public function handle() {
    while (true) {
    
        // if the server is unavailable and,
        // a notification has not been trigger for this instance
        if (!$this->isMyServerAlive() && $this->shouldNotify) {

            // echo notification 
            echo 'The server is down';

            // set it so that a notification is not triggered on next loop
            $this->shouldNotify = false;
        }

        // if the server is again available
        // set it to trigger a notification when it becomes unavailable again
        if ($this->isMyServerAlive()) {
            $this->shouldNotify = true;
        }
    }
}

You would be better scheduling this as a task rather than constantly looping.

  • Related