[笔记]laravel定时任务的实现
1.创建任务执行文件
command php artisan make:command TestTask
会在app\console\Commands 下生成 TestTask.php
2.编辑任务执行文件
class TestTask extends Command
{
protected $signature = 'b5net:test';//命令名,自己随意写
protected $description = '测试任务';//命令描述
public function __construct()
{
parent::__construct();
}
public function handle()
{ //执行的逻辑
file_put_contents('aaa.txt',date('Y-m-d H:i:s').'/r/n',FILE_APPEND);
}
}
3.在app\Console\Kernel.php中引入和设置执行间隔
protected $commands = [
\App\Console\Commands\TestTask::class //引入命令类
];
protected function schedule(Schedule $schedule)
{
$schedule->command('b5net:test')->everyFiveMinutes();//每5分钟执行一次,这里的5分钟,在window设置计划任务时,要把开始分钟数设为5的倍数
}
4.添加服务器的计划任务
linux下使用crontab:自己百度命令
crontab ***** php artisan schedule:run > /dev/null 2>&1
windows下
1.创建xxx.bat文件,内容如下
cd /d D:\Apro_php\b5laravelcmf\ 项目的绝对路径
php artisan schedule:run > NUL 2>&1
2.创建.vbs文件,内容如下
Set ws = CreateObject("Wscript.Shell")
ws.run "cmd /c D:\Apro_php\b5laravelcmf\public\xxx.bat",vbhide
里面的D:\Apro_php\b5laravelcmf\public\xxx.bat为第一步创建的xxx.bat文件的路径。之所以创建.vbs文件,是定时执行.bat文件时会弹出dos界面,执行.vbs是后台静默执行
3.找到任务计划程序创建计划任务
注意这里的1分钟是选择了5分钟,然后手动删除5自己写上的1
本作品采用《CC 协议》,转载必须注明作者和本文链接