laravel做定时任务时,加参数(也可缓存参数)

在command文件中,在命令行中执行php artisan ento:sync-employee ,每执行一次就获取一页数据,100名员工数据信息,然后页数增加1缓存起来,下次执行命令就用该缓存的参数

<?php

namespace AppConsoleCommands;

use IlluminateConsoleCommand;
use GuzzleHttpClient;
use IlluminateSupportFacadesLog;
use AppModelsEmployee;
use AppModelsUser;
use IlluminateSupportFacadesCache;
class SyncEmployeeData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ento:sync-employee';  //这里可以加参数如:'ento:sync-employee {page?}' page就是加的参数,
                                   在命令执行命令时为 php artisan ento:sync-employee 1
                                如何获取到这个page参数:$page =
$this->argument('page');//1
                                该例子使用的也是加参数的形式,但是不用在命令行敲出参数的值,而是每执行一次命令就自增1,每次执行时都会将参数进行缓存
                                 
/** * 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() { $this->info("开始同步员工信息,开始:".date('H:i:s'));//执行命令时命令行显示的信息 $this->getEmployees(); Log::channel('daily')->info('同步员工信息'); $this->info("同步员工信息结束,结束:".date('H:i:s')); } //获取员工信息 private function getEmployees(){ try{ if (Cache::has('employee-page')) { //employee-page就是该例子的参数,也是页数 $page = Cache::get('employee-page'); } else { $page = Cache::set('employee-page', 1);//没有缓存时设置为1 $page = 1; } Cache::increment('employee-page');//执行一次php artisan后employee-page参数就自增1 $pagesize = 100; $base_uri = 'https://api.abc.com'; $apiKey = 'abc'; //密钥 $route = '/au/api/employees?&page[number]='.$page.'&page[size]='.$pagesize; $client = new Client(['base_uri'=>$base_uri]); $response = $client->request('GET', $route, [ 'headers' => [ 'x-api-key' => $apiKey, 'Content-Type' => 'application/vnd.api+json' ] ]); $body = $response->getBody(); $body_result = json_decode($body,true);$this->insert($body_result["data"]);//数据入库 }catch(Exception $e){ Cache::forget('employee-page'); $this->info("报错信息:".$e->getMessage()); Log::channel('daily')->error('同步员工数据出错'.$e->getMessage()); } } //数据入库 private function insert($data){ foreach($data as $key=>$value){ $employee = Employee::updateOrCreate(["id"=>$value["id"]],[ //对应字段数据省略不写 ]); } } }
踩过这个坑,还有下一个坑等着你,这一路就是给自己填坑,坑填多了,也就习惯了,直到这一路平坦了,也就无怨无悔了。
原文地址:https://www.cnblogs.com/xiaofeilin/p/13815204.html