Laravel使用when()方法调度作业

时间:2018-08-17 11:08:52

标签: php laravel

以下代码中的错误在哪里? 在终端中发出php artisan schedule:run命令时出现致命错误。

protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        $forgotCheckout = Working::whereNull('deleted_at')->get();
        $forgot = [];
            foreach($forgotCheckout as $forgot){
                $forgot;
            }
            Mail::send(
                'emails.forgot_checkout',
                compact('forgot'),
                function ($message) use ($forgot) {
                    $message->to('test@email.com');
                    $message->subject('This is test mail');

                }
            );
    })->daily()->when(function ($forgot){
        if(is_null($forgot)){
            return false;
        }
        else{
            return true;
        }
    });
}

Symfony \ Component \ Debug \ Exception \ FatalThrowableError:类型错误:函数App \ Console \ Kernel :: App \ Console {closure}()的参数太少,传递了0个且恰好期望1个

  at C:\www\test\app\Console\Kernel.php:50
    46|                         $message->subject('This is test mail');
    47|
    48|                     }
    49|                 );
  > 50|         })->everyMinute()->when(function ($forgot){
    51|             if(is_null($forgot)){
    52|                 return false;
    53|             }
    54|             else{

2 个答案:

答案 0 :(得分:1)

尝试以下代码。

protected function schedule(Schedule $schedule)
{
    $forgot = [];
    $schedule->call(function () {
        $forgotCheckout = Working::whereNull('deleted_at')->get();

            foreach($forgotCheckout as $forgot){
                $forgot;
            }
            Mail::send(
                'emails.forgot_checkout',
                compact('forgot'),
                function ($message) use ($forgot) {
                    $message->to('test@email.com');
                    $message->subject('This is test mail');

                }
            );
    })->daily()->when(function() use($forgot) {
        if(is_null($forgot)){
            return false;
        }
        else{
            return true;
        }
    });
}

更改的代码行:

->daily()->when(function() use($forgot) {

答案 1 :(得分:0)

如果您查看Illuminate\Console\Scheduling\Event class source code,则方法when将运行Callable对象,而不会传递任何参数。

相反,您的代码需要一个参数:

})->everyMinute()->when(function ($forgot){

因此,您必须更改代码才能使用$forgot变量(在您的方法中对其进行初始化)并像这样更改代码:

})->everyMinute()->when(function () use($forgot){
相关问题