Skip to content
Advertisement

Laravel Task Scheduler always failed

Task Scheduler with call method always fail when I add onFailure callback

Basic test:

// ConsoleKernel.php
$schedule->call(function () {
    var_dump('test');
})
->onFailure(function () {
    var_dump('failed');
})
->everyMinute();

image

I’m wrong somewhere or missing something ?

Thanks in advance

Advertisement

Answer

UPDATE: I submitted a PR to fix this in the Laravel framework and it was just merged. Looks like this will work in Laravel 8 (due to be released next week, I think).

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


It appears that the success/failure hooks do not work with closures.

From looking at the source code, it looks like Laravel is relying on exit codes to determine if a scheduled task was successful or not:

https://github.com/laravel/framework/blob/7.x/src/Illuminate/Console/Scheduling/Event.php#L787

You can see here that it is looking for an exit code other than 0.

The thing is, exit codes are only set when calling scheduled commands via external process:

https://github.com/laravel/framework/blob/7.x/src/Illuminate/Console/Scheduling/Event.php#L222

For a closure (callback) task, there is no updating of the exit code:

https://github.com/laravel/framework/blob/7.x/src/Illuminate/Console/Scheduling/CallbackEvent.php#L75-L85

Which means, the exit code remains null, which is NOT 0, and evaluates to failure.

This might be something the Laravel team would consider improving for a future version. In the meantime, if you write a traditional artisan command and run that via the scheduler, you should find the success/failure hooks working as expected.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement