usleep

Pauses script execution for the given number of microseconds.

Signature
usleep(int $microseconds): void
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$microsecondsintHow long to halt for, in microseconds. One second is 1,000,000 microseconds and one millisecond is 1,000.

Return value

voidNo value is returned.

Errors

Throws a ValueError if microseconds is negative or greater than 4294967295, and a TypeError if the value is not an integer and cannot be coerced to one.

Changelog

  • PHP 8.0A microseconds value below 0 or above 4294967295 now throws a ValueError. Previously an E_WARNING was raised and the call did nothing.

usleep() blocks the current process for a sub-second interval. Where sleep() only takes whole seconds, this takes microseconds, which makes it the right tool for the short pauses real code actually needs: 200 ms between API retries, 50 ms between polls of a job table, a few milliseconds to stay under a rate limit.

Typical patterns

Exponential backoff around a flaky call — sleep, double the delay, try again. Polling loops that would otherwise spin the CPU. Throttling a batch job so it does not saturate a database. Pacing writes to a device or an external service with a documented requests-per-second cap.

Accuracy and cost

The pause is a floor, not a promise. Scheduler granularity and system load routinely add a millisecond or more, so a loop of a thousand 1 ms sleeps will take noticeably longer than one second. Measure with hrtime() rather than assuming. For sleeps longer than a second use sleep(), and for nanosecond granularity or a resumable sleep use time_nanosleep().

The web-request caveat

Every sleeping request still holds its PHP-FPM worker and any open database connections. Sleeping inside a web request to retry an upstream call is a common cause of pool exhaustion under load; push that work to a queue instead.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Backing off between retries when an HTTP API returns 429 or a connection fails
  • Throttling a bulk import loop so it stays under a database or API rate limit
  • Polling a queue or job table without spinning the CPU at full speed
  • Pacing writes to a serial device or hardware that needs a settling delay

Frequently asked questions

How do I sleep for milliseconds in PHP?

Multiply by 1000 and pass the result to usleep(): usleep(250 * 1000) pauses for 250 milliseconds. There is no dedicated millisecond sleep function.

What is the difference between usleep and sleep?

sleep() takes whole seconds, usleep() takes microseconds and so can pause for fractions of a second. For delays longer than one second prefer sleep(), since very large microsecond values are not well supported on every operating system.

Is usleep accurate?

It guarantees a minimum, not an exact duration. System timer granularity, load and the cost of the call itself typically add a fraction of a millisecond or more, so measure real elapsed time with hrtime() if the timing matters.

More examples

Exponential backoff around a flaky call

Prints two failure lines with waits of 10 ms and 20 ms, then 'succeeded on attempt 3'. Doubling the delay each round keeps a struggling dependency from being hammered while still recovering quickly when it comes back.

Example · php
<?php
function flakyCall(int $attempt): bool { return $attempt >= 3; }

$delay = 10_000;
for ($attempt = 1; $attempt <= 5; $attempt++) {
    if (flakyCall($attempt)) {
        echo "succeeded on attempt $attempt\n";
        break;
    }
    echo "attempt $attempt failed, waiting ", $delay / 1000, " ms\n";
    usleep($delay);
    $delay *= 2;
}

Pacing a loop to a fixed rate

Prints five ticks and a total of roughly 250 ms. The measured figure is always a little above the theoretical 250 because each sleep is a minimum and the scheduler adds overhead — never build timing guarantees on the nominal value.

Example · php
<?php
$perSecond = 20;
$interval = intdiv(1_000_000, $perSecond);

$start = hrtime(true);
for ($i = 1; $i <= 5; $i++) {
    echo "tick $i\n";
    usleep($interval);
}
printf("5 ticks paced at %d/s took about %.0f ms\n", $perSecond, (hrtime(true) - $start) / 1_000_000);

Out-of-range values throw

Prints the ValueError saying the argument must be between 0 and 4294967295, then shows that usleep(0) is perfectly legal and returns almost immediately. On PHP 7 the negative call only produced a warning, so code that relied on that silence breaks on PHP 8.

Example · php
<?php
try {
    usleep(-1);
} catch (ValueError $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

$before = hrtime(true);
usleep(0);
printf("usleep(0) returned in %.3f ms\n", (hrtime(true) - $before) / 1_000_000);

Discussion

  • Be the first to comment on this lesson.