在 Linux 上使用 Laravel 定时任务,核心是通过 Laravel Task Scheduling + Linux crontab 来实现。下面一步一步说明。
php artisan make:command SendEmails
生成文件:app/Console/Commands/SendEmails.php
示例:
protected $signature = 'email:send';
protected $description = 'Send emails';
public function handle()
{
// 业务逻辑
\Log::info('Email sent');
}
app/Console/Kernel.php 中注册调度protected function schedule(Schedule $schedule)
{
// 每分钟执行
$schedule->command('email:send')->everyMinute();
// 每天凌晨执行
// $schedule->command('email:send')->daily();
// 自定义时间
// $schedule->command('email:send')->cron('0 2 * * *');
}
crontab -e
* * * * * cd /path/to/laravel && php artisan schedule:run >> /dev/null 2>&1
说明:
* * * * *:每分钟触发一次schedule:run 会检查 Laravel 里定义的任务是否该执行/path/to/laravel 替换为你的项目根目录->everyMinute()
->everyFiveMinutes()
->hourly()
->daily()
->weekly()
->monthly()
->cron('0 3 * * *') // 自定义
php artisan schedule:list
php artisan email:send
storage/logs/laravel.log
php 命令找不到
which php
使用绝对路径,例如:
* * * * * cd /www/laravel && /usr/bin/php artisan schedule:run
权限问题
chown -R www:www storage bootstrap/cache
queue + schedule 配合->appendOutputTo(storage_path('logs/task.log'))
如果你愿意,可以告诉我:
我可以给你更精确的配置示例。