laravle定时任务
参考文档
| 学院君 | 官方说明 [参考] |
|---|---|
| 链接 | 官方说明 link |
1.使用
我们首先使用命令创建定时任务类
php artisan make:command +自定义类名
定义完成之后会在
app\Console\Commands\目录下出现自定义的类
定义完成之后打开项目
dingshitest.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class dingshitest extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
#这里是自定义名称方便后续调用:例我自定义名称为 yao
protected $signature = 'yao';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
#这里写我们的业务逻辑
public function handle()
{ #例子:这里定义每分钟打印一个日志 日志目录在 storage\logs 中
\Log::info('我每分钟执行一次');
}
}
上诉写完之后回到app/Console/Kernel.php
<?php
namespace App\Console;
use App\Console\Commands\dingshitest;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
#laravel5.5一下需要在这里注册自定义的command类,5.5以上的版本忽略
protected $commands = [
//例子
dingshitest::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
#这里是写定时任务的地方
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
#例子 定义每一分钟执行一次自定义的类
$schedule->command('yao')->everyMinute();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
2.开始使用定义完成的定时任务
使用artisan 开启命令
php artisan schedule:run
上诉只是完成了半自动定时任务
我们还需要
crontab脚本自动执行定时任务
|陌生人博客crontab说明|菜鸟教程说明|
|----|----|
|说明|[链接|
我们需要在本地随意一个地方防治一个放置命令的文件
例:yao.txt
然后编写命令
#这条命令就是说每分钟执行一次php artisan schedule:run命令
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
path-to-your-project 换置成您自己的项目目录如果不知道的可以使用
pwd命令查看当前目录
最后这里我们只需要几个简单的crontab命令即可调用定时任务
查看服务器上的定时条目
crontab -l
启用定时任务
crontab yao.txt
打开crontab执行命令,可以删除里面的定时任务
crontab -e
最终效果展示

说明 参考参考视频地址
定时任务命令
| 命令 | 释意 |
|---|---|
| ->cron('* * * * *'); | 在自定义Cron调度上运行任务 |
| ->everyMinute(); | 每分钟运行一次任务 |
| ->everyFiveMinutes(); | 每五分钟运行一次任务 |
| ->everyTenMinutes(); | 每十分钟运行一次任务 |
| ->everyFifteenMinutes(); | 每十五分钟运行一次任务 |
| ->everyThirtyMinutes(); | 每三十分钟运行一次任务 |
| ->hourly(); | 每小时运行一次任务 |
| ->hourlyAt(17); | 每小时第十七分钟运行一次任务 |
| ->daily(); | 每天凌晨零点运行任务 |
| ->dailyAt('13:00'); | 每天13:00运行任务 |
| ->twiceDaily(1, 13); | 每天1:00 & 13:00运行任务 |
| ->weekly(); | 每周运行一次任务 |
| ->monthly(); | 每月运行一次任务 |
| ->monthlyOn(4, '15:00'); | 每月4号15:00运行一次任务 |
| ->quarterly(); | 每个季度运行一次 |
| ->yearly(); | 每年运行一次 |
| ->timezone('America/New_York'); | 设置时区 |

浙公网安备 33010602011771号