为什么PHP Artisan:Schedule Run命令无法执行Artisan命令?

时间:2019-04-03 15:14:04

标签: php laravel laravel-5.7

我运行了php artisan:schedule run命令,它显示了表明命令正在运行的消息。但是,什么也没发生(命令触发的事件),它没有任何作用,那会是什么?

Kernel.php

<?php

    namespace App\Console;

    use App\Console\Commands\CheckPayments;
    use App\Console\Commands\CheckSubscriptions;
    use App\Console\Commands\DeleteOperationalLogs;
    use App\Console\Commands\GenerateInvoices;
    use Illuminate\Console\Scheduling\Schedule;
    use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

    class Kernel extends ConsoleKernel
    {
        protected $commands = [
            CheckPayments::class,
            GenerateInvoices::class,
            CheckSubscriptions::class,
            DeleteOperationalLogs::class
        ];

        protected function schedule(Schedule $schedule)
        {
            $schedule->command(CheckPayments::class, ['--force'])->everyMinute();
            $schedule->command(GenerateInvoices::class, ['--force'])->everyMinute();
            $schedule->command(CheckSubscriptions::class, ['--force'])->everyMinute();
            $schedule->command(DeleteOperationalLogs::class, ['--force'])->everyMinute();
        }

        protected function commands()
        {
            $this->load(__DIR__.'/Commands');

            require base_path('routes/console.php');
        }
    }

运行php artisan schedule后:

Running scheduled command: "C:\xampp\php\php.exe" "artisan" payments:check --force > "NUL" 2>&1
    Running scheduled command: "C:\xampp\php\php.exe" "artisan" subscriptions:check --force > "NUL" 2>&1
    Running scheduled command: "C:\xampp\php\php.exe" "artisan" invoices:generate --force > "NUL" 2>&1
    Running scheduled command: "C:\xampp\php\php.exe" "artisan" logs:delete --force > "NUL" 2>&1

注意:如果我单独运行命令 ,则可以运行,例如:php artisan Payments:check

1 个答案:

答案 0 :(得分:2)

要在调度程序中使用Command,可以使用它的签名或类名。 App\Console\Commands中的每个命令都具有以下内容:

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = "example:command";

一旦将命令导入到App\Console\Kernel.php数组中的protected $commands = [];中,就可以在schedule()函数中使用它,但是使用ExampleCommand::class是不正确的:< / p>

protected function schedule(Schedule $schedule){
  $schedule->command("example:command --force")->everyMinute();
  $schedule->command(ExampleCommand::class, ["--force"])->everyMinute();
  ...
}

这里的主要问题似乎是因为--force选项引发以下错误:

  

“-force”选项不存在

许多现有的Laravel命令都设置了--force标志,该标志在文档中具有以下作用:

  

强制该操作在生产中运行。

许多工匠命令会在您运行诸如php artisan migrate之类的命令时提示输入

  

确定要在生产环境中运行此命令吗?

由于调度程序是非交互式的,因此--force标志会将此提示覆盖为“是”。话虽如此,您需要自己定义和处理该选项:

protected $signature = "example:command {--force}";

public function handle(){
  $force = $this->option("force");
  if(env("APP_ENV", "production") == "production" && !$force){
    if(!$this->ask("Are you sure you want to run this in production?")){
      return false; // or dd();, etc.
    }
  } 
}

未经测试,但是如果在APP_ENV=production中设置了.env,并且$forcenull(如果不包括--force,则为默认值),则它将提示您进行确认,如果回答“否”,则退出。