Laravel 任务调度:用 Scheduler 与自定义 Artisan 命令接管定时作业
test12026-09-2010 次阅读
定时任务别再靠系统 crontab 堆命令
把清理、统计、对账这类定时作业写进 Laravel,好处是逻辑用 PHP 表达、能跑 Eloquent、能注入服务、失败时能触发通知,而且所有调度集中在一个 Kernel 里可读可测。系统侧只需要一条 crontab 不停调用 schedule:run,具体“什么时候跑什么”全在代码里。
先写一个可带选项的 Artisan 命令
命令通过 $signature 声明名称和参数,--dry-run 这种开关用 option 读取。返回 self::SUCCESS / self::FAILURE 决定调度失败与否,从而联动 onFailure 通知。
<?php
// app/Console/Commands/CleanupExpiredTokens.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class CleanupExpiredTokens extends Command
{
protected $signature = 'tokens:cleanup {--dry-run : 只统计不删除}';
protected $description = '清理过期的访问令牌';
public function handle(): int
{
$query = DB::table('personal_access_tokens')
->where('expires_at', '<', now());
if ($this->option('dry-run')) {
$this->info("待清理: {$query->count()} 条");
return self::SUCCESS;
}
$deleted = $query->delete();
$this->info("已清理: {$deleted} 条过期令牌");
return self::SUCCESS;
}
}
在 Kernel 里声明调度
schedule 方法用链式 API 表达频率与时机:dailyAt 指定每天几点,weekly()->sundays()->at 指定每周日。每个调度都能挂 onFailure、pingOnSuccess 等钩子。
<?php
// app/Console/Kernel.php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected function schedule(Schedule $schedule): void
{
$schedule->command('tokens:cleanup')
->dailyAt('03:30')
->onFailure(function () {
// 这里发失败通知
});
$schedule->command('tokens:cleanup --dry-run')
->weekly()
->sundays()
->at('09:00');
}
}
系统侧只需一条 crontab
调度表达式全在 PHP 里维护,服务器只要保证每分钟触发一次 schedule:run,它自己会判断哪些任务到点该执行。
* * * * * cd /path/to/app && php artisan schedule:run >> /dev/null 2>&1
工程收益
- 定时逻辑用 PHP 写,能直接用模型、缓存和服务容器。
- 所有任务集中在 Kernel,可读、可单元测试、可版本管理。
- 失败钩子与通知内置,比裸 shell 脚本更可控。
T
test1
文章作者
定时任务别再靠系统 crontab 堆命令 把清理、统计、对账这类定时作业写进 Laravel,好处是逻辑用 PHP...
- 分类
- 技术
- 发布时间
- 2026-09-20
- 字数
- 约 2117 字
- 阅读
- 10 次
