Sleep

PHP Time Function: Sleep

usleep()

usleep(int $microseconds): void

Delay execution in microseconds

// Current time
echo (new DateTime('now'))->format('H:i:s.v'), "\n";

// wait for 2 milliseconds
usleep(2000);

// back!
echo (new DateTime('now'))->format('H:i:s.v'), "\n";

// wait for 30 milliseconds
usleep(30000);

// back again!
echo (new DateTime('now'))->format('H:i:s.v'), "\n";

sleep()

sleep(int $seconds): int

Delay execution in seconds

// current time
echo date('h:i:s') . "\n";

// sleep for 10 seconds
sleep(10);

// wake up !
echo date('h:i:s') . "\n";

Helper function

class TimeSupport
{

    /**
     * @param int $seconds
     * @return int
     */
    public static function secondsToMilliseconds(int $seconds)
    {
        return (int) ($seconds * 1000000);
    }

    /**
     * @param int $min_seconds
     * @param int $max_seconds
     * @return int
     */
    public static function getRandomSleepRange(int $min_seconds = 1, int $max_seconds = 3)
    {
        $min_milliseconds = static::secondsToMilliseconds($min_seconds);
        $max_milliseconds = static::secondsToMilliseconds($max_seconds);

        return rand($min_milliseconds, $max_milliseconds);
    }

    /**
     * @param int $min_seconds
     * @param int $max_seconds
     * @return int
     */
    public static function sleepRange(int $min_seconds = 1, int $max_seconds = 3)
    {
        $sleep_milliseconds = static::getRandomSleepRange($min_seconds, $max_seconds);
        usleep($sleep_milliseconds);
        return (float) $sleep_milliseconds / 1000000;
    }
}