在 Debian 下为 Laravel 设置定时任务,核心就是 使用 Linux 的 crontab 来调用 Laravel 的调度器(schedule)。下面按步骤说明。
Laravel 本身不单独管理定时任务,而是:
php artisan schedule:run
app/Console/Kernel.php 的 schedule() 方法中nano app/Console/Kernel.php
例如:
protected function schedule(Schedule $schedule)
{
// 每分钟执行一次
$schedule->command('emails:send')->everyMinute();
// 每天凌晨执行
$schedule->command('backup:run')->daily();
}
常见频率:
| 方法 | 说明 |
|---|---|
->everyMinute() |
每分钟 |
->hourly() |
每小时 |
->daily() |
每天 00:00 |
->dailyAt('02:30') |
每天 2:30 |
->weekly() |
每周 |
->monthly() |
每月 |
⚠️ 不要用 root 跑 Laravel(除非你很清楚)
sudo su - www-data
# 或
sudo su - youruser
crontab -e
* * * * * cd /var/www/your-laravel-project && php artisan schedule:run >> /dev/null 2>&1
✅ 含义:
* * * * *:每分钟执行cd /var/www/your-laravel-project:进入项目目录php artisan schedule:run:运行 Laravel 调度器查看 PHP 路径:
which php
如果输出是:
/usr/bin/php
那就写成:
* * * * * cd /var/www/your-laravel-project && /usr/bin/php artisan schedule:run >> /dev/null 2>&1
sudo systemctl status cron
或:
grep CRON /var/log/syslog
在 Kernel 中先测试:
$schedule->call(function () {
\Log::info('cron test');
})->everyMinute();
然后查看:
tail -f storage/logs/laravel.log
sudo chown -R www-data:www-data storage bootstrap/cache
php -v
如果 Web 和 CLI 版本不同,指定完整路径:
/usr/bin/php8.2 artisan schedule:run
sudo systemctl enable cron
sudo systemctl start cron
crontab -e
* * * * * cd /var/www/laravel && php artisan schedule:run >> /dev/null 2>&1
然后在 Kernel.php 里写你的定时逻辑 ✅
如果你愿意,我可以帮你:
直接把你的 Debian 版本 + PHP 版本 + Laravel 版本发我即可。