123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- <?php
- namespace App\Crontab;
- use EasySwoole\Crontab\JobInterface;
- use App\Com\SmtpSend;
- use EasySwoole\EasySwoole\Config;
- use App\Models\WarningBody;
- use EasySwoole\Mysqli\QueryBuilder;
- use EasySwoole\ORM\DbManager;
- use EasySwoole\EasySwoole\Logger;
- /**
- * 任务说明:每10分钟抓取30分钟内更新的商品内容,
- * 使用福利api提供的接口推送到Es搜索引擎中
- */
- class ElasticSearchGoodsCrontab implements JobInterface
- {
- public function jobName(): string
- {
- // 定时任务的名称
- return 'ElasticSearchGoodsCrontab';
- }
- public function crontabRule(): string
- {
- // 定义执行规则 根据 Crontab 来定义
- // 这里是每10分钟执行 1 次
- return '*/10 * * * *';
- }
- public function run()
- {
- //定时任务的执行逻辑
- $welfare_api_set = Config::getInstance()->getConf('WELFARE_API');
- $page = 1;
- while (true) {
- $goods = $this->getUpdateGoods($page);
- if (!$goods) {
- break;
- } else {
- $page++;
- }
- foreach($goods as $key=>$value){
- $res = $this->http_request(
- $welfare_api_set['url'],
- ['goodsid'=>$value['id'],'goods_body'=>json_encode($value)]
- );
- //返回内容写入日志
- Logger::getInstance()->notice("商品ID{$value['id']}导入结果:{$res}\n");
- }
- }
- }
- //获取30分钟内更新过的商品记录
- protected function getUpdateGoods($page = 1)
- {
- $size = 50;
- $offset = ($page - 1) * $size;
- $where = ' g.`updatetime`>'.(time()-1800); //30分钟内更新的商品
- $que_sql = "SELECT * FROM ims_superdesk_shop_goods g
- WHERE {$where}
- LIMIT {$offset},{$size}
- ";
- $queryBuild = new QueryBuilder();
- $queryBuild->raw($que_sql);
- $res_data = DbManager::getInstance()->query($queryBuild, true, 'default')->toArray();
- return $res_data['result'];
- }
- /**
- * http请求
- * @param $url 请求地址
- * @param $data 数组内容
- * @return String 请求返回原生数据
- */
- protected function http_request($url,$data){
- $opts = array(
- 'http' => array(
- 'method' => 'POST',
- 'header' => "Content-type:application/x-www-form-urlencoded",
- 'content' => http_build_query($data),
- )
- );
- $context = stream_context_create($opts);
- $response = file_get_contents($url,false,$context);
- return $response;
- }
- public function onException(\Throwable $throwable)
- {
- // 捕获 run 方法内所抛出的异常
- }
- }
|