任务调度
在环境中增加任务条目,使系统每分钟执行你laravel中的任务
sudo vim /etc/crontab
在最后一行加入这句话
* * * * * root php /var/www/Cms/artisan schedule:run >> /dev/null 2>&1
在app\Console\Commands下面是php artisan命令的文件,现在我们也需要创建一个
php artisan make:console Test
Test.php 就可以看到了
class Test extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'flashApi:start'; // 这里是命令
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command getDataByFlashPApi';
/**
* Create a new command instance.
*
* @return void
*/
protected static $newsFlashService = null;
public function __construct(NewsFlashService $newsFlashService)
{
parent::__construct();
self::$newsFlashService = $newsFlashService;
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->getDataByTemApi();
}
/**
* 接口数据获取
*
* @return array
* @author jacklin
*/
public function getDataByTemApi()
{
// 接口开关 默认为true
$switch = Redis::get('STRING:FLASH:SWITCH:STATUS');
if ($switch==2) return Common::returnResponse(411);
// 执行自动添加接口
$res = self::$newsFlashService->addDataByTemApi();
Log::info('=======>快讯接口本次请求添加的数据条数为:');
Log::info($res);
}
}
创建好这个文件,在根目录再执行php artisan 就可以看到我们这个命令,以及命令描述
然后,我们需要用linux的任务调度来执行这个命令,做法就是在app\Console\Kernel.php中注册这条命令,以及规定这条命令的执行频次。
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\Test::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('flashApi:start')->everyMinute();// 定义命令每分钟执行
}
}
值得一说的是$schedule 不只有执行命令的command()方法,还有call()方法来执行某个控制器的某方法;
mac下面,不能用环境变量, 要写php 命令的绝对命令
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: