在 Linux 上使用 Laravel 实现“定时任务”,核心就是 Linux 的 cron + Laravel 的 Task Scheduling。下面一步一步说明。
Laravel 自带任务调度器(schedule),你只需要:
routes/console.php 或 app/Console/Kernel.php 中定义任务crontab 中只加一条 cronroutes/console.php
use Illuminate\Support\Facades\Schedule;
Schedule::call(function () {
// 你要执行的代码
\Log::info('定时任务执行了');
})->everyMinute();
php artisan make:command SendEmails
app/Console/Commands/SendEmails.phpprotected $signature = 'send:emails';
public function handle()
{
// 业务逻辑
\Log::info('发送邮件');
}
app/Console/Kernel.phpprotected function schedule(Schedule $schedule)
{
$schedule->command('send:emails')->dailyAt('09:00');
}
crontab -e
* * * * * cd /path/to/laravel && php artisan schedule:run >> /dev/null 2>&1
示例:
* * * * * cd /var/www/laravel && php artisan schedule:run >> /dev/null 2>&1
意思是:每分钟让 Laravel 检查一次是否有任务需要执行
->everyMinute();
->everyFiveMinutes();
->hourly();
->daily();
->dailyAt('13:30');
->weekly();
->monthly();
->cron('0 0 * * 0');
✅ 检查:
php artisan schedule:run
✅ 检查日志:
storage/logs/laravel.log
✅ cron 是否运行:
service cron status
# 或
systemctl status cron
确保:
php 可执行storage 可写$schedule->command('send:emails')->daily()->onQueue();
或命令里 dispatch(new Job())
✅ Linux 只配一条 cron
✅ Laravel 用 schedule 管理时间
✅ 推荐用 Artisan Command
如果你愿意,可以告诉我:
我可以给你完整可直接用的示例。