我正在创建一个自定义命令,该命令将在控制台内核中每隔30分钟截断一个表(出于开发目的)。我想在前一个命令之后再运行另一个命令。
附言:我有一个if语句,它阻止在生产服务器上运行这些命令。
$schedule->command('db:seed')->after(function () use ($schedule) : void {
$schedule->command('my-command:remove-users-from-tables')
->everyThirtyMinutes()
->environments(['demo', 'local']);
});我希望在"my-command“每30分钟成功运行一次之后立即运行播种器。但是,在这种情况下,只有db:seed运行。
发布于 2019-06-20 12:02:23
我已经检查了Illuminate\Console\Scheduling\Schedule类的源代码。
我认为当我们说:
$schedule->command(...);artisan命令将被排定,而不是直接运行。
所以当你这样写的时候:
$schedule->command('first-command')->after(function () use ($schedule) {
$schedule->command('second-command');
});第二个命令将被注册,而不是在第一个命令之后立即运行。
因此,我能想到的最佳方法是根据this link在第一个命令中运行第二个命令
您可以尝试如下所示:
namespace App\Console\Commands;
use Illuminate\Console\Command;
class RemoveUsersFromTable extends Command
{
public function handle()
{
// Do something to remove users from table.
$this->call('db:seed');
}
} 发布于 2021-02-15 09:18:27
另一种在某些情况下可能相关的替代方案(但我可以想象在其他情况下也不是一个好主意)是运行shell_exec:https://www.php.net/manual/en/function.shell-exec.php
如果您想要像在cli上那样使用&&将两个artisan命令链接在一起,您可以简单地使用shell_exec('php artisan command:first && php artisan command:second')。
shell_exec返回控制台输出,所以如果您的命令打印任何东西(即通过$this->info),那么您可以像这样将其打印到控制台:$this->info(shell_exec('php artisan command:first && php artisan command:second'))
我可能会因为这个答案而招来很多人的讨厌……
https://stackoverflow.com/questions/56669746
复制相似问题