The Sleep Class
A testable, expressive wrapper around PHP's sleep functions with a fluent API.
Overview
The Illuminate\Support\Sleep class provides an object-oriented, testable replacement for PHP's sleep() and usleep() functions.
Usage
use Illuminate\Support\Sleep;
// Sleep for 2 seconds
Sleep::for(2)->seconds();
// Sleep for 500 milliseconds
Sleep::for(500)->milliseconds();
// Sleep until a specific time
Sleep::until(now()->addMinute());
In tests, you can fake it:
Sleep::fake();
// Run code that sleeps...
Sleep::assertSleptTimes(3);
Sleep::assertSequence([
Sleep::for(1)->second(),
Sleep::for(2)->seconds(),
Sleep::for(3)->seconds(),
]);
When to Use
- Rate limiting in artisan commands
- Retry logic with backoff
- Any time you need
sleep()but want it testable