iTranslated by AI
What Exactly is Laravel's Sleep Class?
Introduction
While looking through the release notes for Laravel 10.31.0, I noticed something called Sleep::until(). I wondered, "What on earth is the Sleep class!?" so I decided to look into it a bit.
Environment
- Laravel 10.31.0
What is the Sleep class??
It is a class added in Laravel 10.10.0 and seems to be a wrapper class for the native PHP sleep and usleep functions.
Looking at the pull request when it was added, it was initially named Siesta, but it changed along the way.
What can it do??
Since it is a wrapper for the sleep and usleep functions, it can naturally do the same things.
use Illuminate\Support\Sleep;
sleep(2);
usleep(5000);
// Using the Sleep class, it's written as follows:
Sleep::for(2)->seconds(); // Stop for 2 seconds
Sleep::sleep(2); // Alias for the sleep function
Sleep::for(5000)->microseconds(); // Stop for 5000 microseconds
Sleep::usleep(5000); // Alias for the usleep function
In addition, it seems possible to specify minutes and milliseconds as well.
use Illuminate\Support\Sleep;
Sleep::for(1)->minutes(); // Stop for 1 minute
Sleep::for(100)->milliseconds(); // Stop for 100 milliseconds
If you just want to stop execution, you could use native functions, but the advantage of using the wrapper seems to be making it testable (this is also mentioned in the pull request).
If code like sleep(2); is in your logic, the test will actually wait for 2 seconds, making test execution significantly slower.
Therefore, by using the Sleep class, it becomes possible to mock it, allowing tests to run without actually waiting for 2 seconds.
Sleep::sleep(2);
use Illuminate\Support\Sleep;
Sleep::fake();
// Assert how many times the Sleep class was executed
Sleep::assertSleptTimes(1);
// Assert how many seconds the Sleep class stayed stopped
Sleep::assertSequence([
Sleep::for(3)->seconds(),
]);
Besides that, there are various things written in the manual.
Conclusion
Personally, I don't have many opportunities to use the sleep and usleep functions, so I'm not sure how practical it is...
However, considering the ease of writing tests, it might be better to use the Sleep class.
Reference
Discussion