温馨提示×

linux laravel怎么写定时任务

小樊
39
2026-09-25 11:38:50
栏目: 智能运维

在 Linux 下使用 Laravel 定时任务,一般分两步:

  1. 写 Laravel 任务(Command / 调度)
  2. 在 Linux 上配置 Cron,只调用 Laravel 的 schedule

一、创建 Laravel 定时任务

1. 创建 Artisan 命令

php artisan make:command SendEmails

生成文件:app/Console/Commands/SendEmails.php

2. 编写命令逻辑

protected $signature = 'send:emails';
protected $description = '发送邮件';

public function handle()
{
    // 你的业务逻辑
    \Log::info('定时任务执行了');
}

二、在 Laravel 中注册调度

编辑 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()

三、Linux 配置 Cron(关键)

1. 编辑 crontab

crontab -e

2. 添加一行(最重要)

* * * * * 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 会自己管理所有任务时间


四、常见问题

1. 权限问题

确保:

  • php 命令可用
  • Laravel 目录可写(storage, bootstrap/cache)

2. 查看是否执行

php artisan schedule:list

3. 手动测试命令

php artisan send:emails

五、示例完整流程

php artisan make:command BackupDB
# 写逻辑
# Kernel.php 中 schedule
# crontab -e 添加 schedule:run

如果你愿意,可以告诉我:

  • Laravel 版本
  • 想做「每分钟 / 每天 / 每周」什么任务

我可以直接帮你写完整代码。

0 踩