Home > other >  How to create a timer to check a condition after a while in PHP?
How to create a timer to check a condition after a while in PHP?

Time:10-19

I need to create a PHP timer to check a condition.I'll explain,i have a function named getMsg(),i need to check if getMsg is called within 60 sec using that timer,if not then do somw work,and if yes then reset the timer for the next 60 secs.

function getMsg()
{
   //some codes
   checkTimer();  //check if the getMsg() function is called within 60 secs or not
   function checTimer(){
     //function body
   }
}

CodePudding user response:

I guess that you will need to use session variables to "remember" last timestamp. The code below saves the current timestamp between each call to your php module. The function CheckTimer will return true if 60 seconds or more have elapsed since last time:

<?php
session_start();

function CheckTimer() {
    // Check if there's a previous saved timestamp, 
    // ... or use current time (first time you call the function)
    $prev_time = $_SESSION['PrevTime'] ?? time();
    
    $now = time();
    $diff = $now - $prev_time;     // Calculate seconds since last call
    $_SESSION['PrevTime'] = $now;  // Save current timestamp for next call

    return ($diff >= 60);
}

function getMsg() {
    if (CheckTimer()) {
        // Your code if 60 seconds have elapsed
        echo "60 seconds have elapsed";
    } else {
        // Your code otherwise
        echo "Less than 60 seconds have elapsed";
    }
}

getMsg();
?>

CodePudding user response:

The question is not clear but it seems like you need an event-listener here.

  • Related