Running your PHP scripts is an instant job, which means running as fast as possible. In nearly all cases this is what you want. Whether that be via the command line to batch process something or a user visiting or website. Performance can hurt the user experience, that's why it's generally good programming practice to adopt a methodology code efficiently. One way that can be achieved is breaking out of a loop early in PHP once you've finished processing the loop data. However, there are times when you might need to temporarily pause the execution of the PHP script you're running. Let's explore why this might be the case.
Why use PHP sleep?
One example of using PHP sleep is using an API. An API (application programming interface) allows you to connect one system to another via a common set of rule sets. Using an API or building your own one and letting someone else use it is a great way to send data from one place to another. However, there are times with APIs when data cannot be processed as instantly as you'd like, or in another way, cannot be processed immediately as you send it over. Let's say you have sent data via an API to an external service that is undergoing a heavy load. They might reject your request, so, you'll have to re-try the request again at another time. Instead of killing or letting your script run to an end, without having to spawn another PHP process to try again, you could, keep the same script running but pause its output. This is used in an algorithm technique called exponential backoff, where you slowly increase the sleep time of each call before stopping the requests altogether.
What does PHP sleep do?
Using PHP sleep will delay the execution of your script until the time specified has passed. It can be used anywhere in the codebase including loops.
How do you use PHP sleep?
Sleep function requires one parameter, an int, which is the amount of time in seconds that you want to halt the execution. Your integer must be greater than zero.
If you wanted to pause your PHP script by 5 seconds or 1 second you would add the following to your codebase.
// Sleep for five seconds
sleep(5);
// Sleep for 1 second
sleep(1);
With PHP sleep you can't pause the execution in microseconds, due to the function expecting a whole number above 0. Therefore, setting the seconds to 0.5 will pause the script for no seconds, effectively doing nothing. In order to sleep for 0.5 seconds, you instead, you need a function called usleep, to do such things.
The sleep function on success returns int zero, which follows exit code 0. If interrupted by a signal, the function will return the total number of seconds remaining in the sleep cycle. A signal is an operating system event to indicate events to processes. Therefore, when a signal is received, the PHP sleep function is interrupted and the script continues execution. This is useful where you want to handle interrupts gracefully or ensure that your script doesn't hang indefinitely. This can be coupled with "ticks".
PHP Ticks
In PHP it is possible to tell the engine how often the script should check for pending signals. We define this using the declare() function passing ticks and the tick value. A "tick" in computing is a unit of work that the script performs. When setting this to a value of 1, PHP will tick after each statement, or in other words, after each statement is executed, the script checks for pending signals. This is particularly useful when dealing with signal handling in PHP, for example when using the pcntl_signal function. When using PHP on the command line or when you are running long scripts this is particularly useful.
declare(ticks=1);
It's worth noting that in PHP 8 and above, passing negative integers now triggers a fatal error (ValueError) where false was returned previously with a subsequent E_WARNING.
PHP sleep vs usleep?
For pausing PHP anything under a second or usleep for anything over a second use sleep. Some operating systems may not support using usleep for over a second period, but usleep can be used to give you a higher level of precision if that's required. When using usleep its purpose is to pause time in microseconds (1/1000000 of a second) where the time is equal to or lower than 1 second. That's because some operating systems may not support values larger than 1000000.
Sleep function usages
There are many situations the sleep function can be used in PHP applications. As mentioned already, when interacting with APIs the function can be used to control processing rates, typically found in rate-limiting situations. Another fun, yet common use of sleep() function is animation inside a script. Here you could sleep for one second after which you output a full stop (period) to simulate loading processing. Try running the below code to see it in action.
echo "Loading";
sleep(1);
echo ".";
sleep(1);
echo ".";
sleep(1);
echo ".";
PHP sleep function recap
- Always pass an int above 1, as negative numbers will throw a ValueError in PHP version 8+
- Don't pass fractions
- If you want to use fractions or microseconds use usleep function or just as an alternative option
- Sleeping either with sleep or the usleep function will affect the performance of the running script so avoid adding to PHP code that runs in a public-facing area