在 Linux 下使用 Laravel 定时任务,一般分两步:
php artisan make:command SendEmails
生成文件:app/Console/Commands/SendEmails.php
protected $signature = 'send:emails';
protected $description = '发送邮件';
public function handle()
{
// 你的业务逻辑
\Log::info('定时任务执行了');
}
编辑 app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
// 每分钟执行
$schedule->command('send:emails')->everyMinute();
// 每天凌晨执行
// $schedule->command('send:emails')->daily();
// 每周一 9 点
// $schedule->command('send:emails')->weeklyOn(1, '9:00');
}
常用时间方法:
everyMinute()everyFiveMinutes()hourly()daily()dailyAt('13:00')weekly()monthly()crontab -e
* * * * * cd /path/to/laravel && php artisan schedule:run >> /dev/null 2>&1
示例:
* * * * * cd /var/www/laravel && php artisan schedule:run >> /tmp/laravel.log 2>&1
✅ 只需这一条 cron,Laravel 会自己管理所有任务时间
确保:
php 命令可用storage, bootstrap/cache)php artisan schedule:list
php artisan send:emails
php artisan make:command BackupDB
# 写逻辑
# Kernel.php 中 schedule
# crontab -e 添加 schedule:run
如果你愿意,可以告诉我:
我可以直接帮你写完整代码。