You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重写Laravel核心类的特定方法?以ScheduleRunCommand::handle()为例

实现方案(无核心文件修改)

1. 创建自定义调度命令类

在app/Console/Commands目录下新建CustomScheduleRunCommand.php,继承核心ScheduleRunCommand并重写handle方法,仅修改无任务运行时的输出逻辑:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Console\Scheduling\ScheduleRunCommand as BaseScheduleRunCommand;
use Illuminate\Console\Scheduling\Events\ScheduledTaskSkipped;

class CustomScheduleRunCommand extends BaseScheduleRunCommand
{
    public function handle(Schedule $schedule, Dispatcher $dispatcher, ExceptionHandler $handler)
    {
        $this->schedule = $schedule;
        $this->dispatcher = $dispatcher;
        $this->handler = $handler;

        foreach ($this->schedule->dueEvents($this->laravel) as $event) {
            if (! $event->filtersPass($this->laravel)) {
                $this->dispatcher->dispatch(new ScheduledTaskSkipped($event));

                continue;
            }

            if ($event->onOneServer) {
                $this->runSingleServerEvent($event);
            } else {
                $this->runEvent($event);
            }

            $this->eventsRan = true;
        }

        if (! $this->eventsRan) {
            // 加入当前时间戳到输出内容
            $this->info(sprintf('[%s] No scheduled commands are ready to run.', now()->toDateTimeString()));
        }
    }
}

2. 注册自定义命令覆盖核心绑定

打开app/Providers/AppServiceProvider.php,在register方法中添加如下绑定逻辑,让Laravel调用你自定义的命令而非核心原命令:

public function register()
{
    $this->app->bind('command.schedule:run', function ($app) {
        return new \App\Console\Commands\CustomScheduleRunCommand();
    });
}

3. 验证效果

执行php artisan schedule:run,当无待运行调度任务时,输出的提示信息将自动携带当前时间戳。

内容的提问来源于stack exchange,提问作者meatatarian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:57:03