iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌿

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.
https://laravel-news.com/laravel-10-31-0

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.

https://laravel-news.com/laravel-10-10-0

Looking at the pull request when it was added, it was initially named Siesta, but it changed along the way.

https://github.com/laravel/framework/pull/46904

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.
https://laravel.com/docs/10.x/helpers#sleep

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

https://qiita.com/craig-sen/items/57c33e145d76f91ce6ea

GitHubで編集を提案

Discussion