**
windows下laravel的定时任务
**
在项目根目录生成作类命令文件:
php artisan make:command RecordLog
该文件在App\Console\Commands里面
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class RecordLog extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'Log:record'; //名字随便写,后续任务会用到
/**
* The console command description.
*
* @var string
*/
protected $description = '定时记录日志'; //定时任务的描述,没有什么实际作用
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//任务的具体内容
//例如:记录信息到log
Log::info(date('Y-m-d H:i:s').'使用command()方法实现定时任务');
}
}
定时命令创建好之后,需要修改App/Console/Kernel.php 文件 编写命令的调度时间。
<?php
namespace App\Console;
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
*/
protected $commands = [
//注册对应的command类 刚刚创建的命令类
\App\Console\Commands\RecordLog::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// command('Log:record')里面填写之前在RecordLog文件里面的$signature参数
// everyMinute()此为每分钟执行任务
$schedule->command('Log:record')->everyMinute();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
之后可以在终端或者黑窗口执行php artisan schedule:run 测试是否成功
测试结果可以在日志文件里面查看。
编写脚本文件
新建文本
输入
cd 你的项目路径
php artisan schedule:run > NUL 2>&1
保存之后文件更改为 .bat后缀
之后创建windows的任务计划
win+R输入 taskschd.msc 进入任务计划程序
添加完之后就可以生效了。但是。。。。。。。。。。。。。。
后续它每次执行都会跳出来黑窗口。让人好生厌烦。
解决方法:
第一个是通过编写vbs文件让任务静默执行
接着回到任务计划程序,找到之前创建的任务双击
到这里就不会再出现黑窗口了~