How to use sleep and usleep in PHP 8

Description

In PHP 8 the sleep function is most usable if you use it in background jobs. Using sleep while serving HTTP requests from users would be counterproductive and reduce efficiency. Using sleep() it is possible to delay a function that comes afterwards. If we wanted to wait in PHP until a keypress occurred, we would rather use the freads function which does the waiting for us.

sleep in PHP 8

sleep(int $seconds): int

The sleep() function takes a single argument $seconds which indicates the amount of seconds the function should wait/halt. If the function succeeds, it will return 0. On error, it will return false. On Windows machines, an interrupt will cause the function to return the constant WAIT_IO_COMPLETION with the number 192 (read more here) whereas on other operating systems it will return the remaining amount of seconds that the function would have waited had the interrupt not occurred.

Example

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

// sleep for 30 seconds
sleep(30);

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

If you started the program at around 6:30, it would output the following results. As you can see, the number of seconds increased by 30 seconds. Hence the sleep() caused this little script to pause.

06:30:05
06:30:35

usleep in PHP 8

usleep(int $microseconds): void

Alternatively to sleep(), you can use PHP 8's usleep() function with a finer control. usleep allows you to set the amount of microseconds for the script to wait by using the $microseconds argument. As a reminder, 1,000,000 microseconds equal 1 second. This function does not return a success indicator.

Example

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

// sleep for 3 seconds
usleep(3000000);

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

If you started the program at around 8:30, it would output the following results. As you can see, the number of seconds increased by 3 seconds.

08:30:05
08:30:08