newman / laravel-delay
Laravel 延迟助手包
1.2.0
2023-03-08 17:34 UTC
Requires
- php: ^8.0
- illuminate/contracts: ^8.12|^9.0|^10.0
- illuminate/support: ^8.12|^9.0|^10.0
- nesbot/carbon: ^2.13
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- nunomaduro/larastan: ^1.0|^2.4
- orchestra/testbench: ^6.0|^7.0|^8.0
- phpunit/phpunit: ^8.0|^9.0
README
这个包可以帮助你在代码中延迟(暂停)执行一段时间。
继续前请注意
从 Laravel 版本 10.10.0 开始,你可能不再需要这个包,因为已经内置了辅助函数 - https://laravel.net.cn/docs/10.x/helpers#sleep
安装
要求
- Laravel 8.12+,9.0+,10.0+
- PHP 8.0
安装
使用 Composer 安装包
composer require newman/laravel-delay
📖 使用方法
作为 Facade 使用
use Newman\LaravelDelay\Facades\Delay; // ... Delay::for(3);
作为 Trait 使用
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Newman\LaravelDelay\Traits\Delayable; class ImportTask extends Command { use Delayable; // ... }
然后在代码中,你可以这样调用延迟执行
$this->delay()->for(5);
或者
$this->delay(5);
两者都会延迟执行 5 秒。
你可以在任何你想要使用的类中包含 trait,包括控制器。
作为服务容器使用
use Newman\LaravelDelay\Contracts\DelayContract; // ... app()->make(DelayContract::class)->for(5);
使用示例
假设我们使用 Trait。
延迟执行 10 秒
$this->delay(10); $this->delay()->for(10); $this->delay()->forSeconds(10);
注意,如果你想要延迟到秒的分数,你应该使用 forMs
函数。
延迟执行 1500 毫秒(1.5 秒)
$this->delay()->forMs(1500); $this->delay()->forMiliseconds(1500);
延迟执行 5000 微秒(0.005 秒)
$this->delay()->forMicroseconds(5000);
延迟执行到给定的 Carbon 日期时间
$this->delay()->till(Carbon::now()->addMinutes(5)->addSeconds(15));
仅在某些环境/-s 上延迟执行 10 秒
$this->delay()->for(10)->environments(['production']); // delays only on production $this->delay()->for(10)->environments(['production', 'staging']); // delays on production and staging only
除给定环境/-s 外延迟执行 10 秒
$this->delay()->for(10)->except(['prodction']); // delays on all environments, except production $this->delay()->for(10)->except(['prodction', 'staging']); // delays on all environments, except production and staging
仅在回调返回 false 时延迟执行 10 秒
$this->delay()->for(10)->exceptWhen(fn () => 1 + 1 == 2); // code will not delay in this case, because callback returns true $this->delay()->for(10)->exceptWhen(fn () => 1 + 1 == 3); // code will delay in this case, because callback returns false
并且我们可以传递多个回调。
$this->delay()->for(10)->exceptWhen(fn () => false)->exceptWhen(fn () => false); // code will delay $this->delay()->for(10)->exceptWhen(fn () => true)->exceptWhen(fn () => false); // code will not delay, because all callbacks doesn't return false
最后,我们可以链式添加多个条件
它将在生产环境和预发布环境中延迟 10 秒,并且仅在不是上午 10 点时。
$this->delay() ->for(10) ->environments(['production', 'staging']) ->exceptWhen(fn () => Carbon::now()->hour == 10);
🤝 贡献
我们将非常感谢你对这个包的合作。
在创建 pull request 时,请确保
- 所有测试都通过:
composer test
- 测试覆盖率没有降低:
composer test-coverage
- 没有 PHPStan 错误:
composer phpstan
- 遵循编码标准:
composer lint
或composer fix-style
以自动修复。