ElasticSearchGoodsCrontab.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Crontab;
  3. use EasySwoole\Crontab\JobInterface;
  4. use App\Com\SmtpSend;
  5. use EasySwoole\EasySwoole\Config;
  6. use App\Models\WarningBody;
  7. use EasySwoole\Mysqli\QueryBuilder;
  8. use EasySwoole\ORM\DbManager;
  9. use EasySwoole\EasySwoole\Logger;
  10. /**
  11. * 任务说明:每10分钟抓取30分钟内更新的商品内容,
  12. * 使用福利api提供的接口推送到Es搜索引擎中
  13. */
  14. class ElasticSearchGoodsCrontab implements JobInterface
  15. {
  16. public function jobName(): string
  17. {
  18. // 定时任务的名称
  19. return 'ElasticSearchGoodsCrontab';
  20. }
  21. public function crontabRule(): string
  22. {
  23. // 定义执行规则 根据 Crontab 来定义
  24. // 这里是每10分钟执行 1 次
  25. return '*/10 * * * *';
  26. }
  27. public function run()
  28. {
  29. //定时任务的执行逻辑
  30. $welfare_api_set = Config::getInstance()->getConf('WELFARE_API');
  31. $goods = $this->getUpdateGoods();
  32. foreach($goods as $key=>$value){
  33. $res = $this->http_request(
  34. $welfare_api_set['url'],
  35. ['goodsid'=>$value['id'],'goods_body'=>json_encode($value)]
  36. );
  37. //返回内容写入日志
  38. Logger::getInstance()->notice("商品ID{$value['id']}导入结果:{$res}\n");
  39. }
  40. }
  41. //获取30分钟内更新过的商品记录
  42. protected function getUpdateGoods()
  43. {
  44. $where = ' g.`updatetime`>'.(time()-1800); //30分钟内更新的商品
  45. $que_sql = "SELECT * FROM ims_superdesk_shop_goods g
  46. WHERE {$where};
  47. ";
  48. $queryBuild = new QueryBuilder();
  49. $queryBuild->raw($que_sql);
  50. $res_data = DbManager::getInstance()->query($queryBuild, true, 'default')->toArray();
  51. return $res_data['result'];
  52. }
  53. /**
  54. * http请求
  55. * @param $url 请求地址
  56. * @param $data 数组内容
  57. * @return String 请求返回原生数据
  58. */
  59. protected function http_request($url,$data){
  60. $opts = array(
  61. 'http' => array(
  62. 'method' => 'POST',
  63. 'header' => "Content-type:application/x-www-form-urlencoded",
  64. 'content' => http_build_query($data),
  65. )
  66. );
  67. $context = stream_context_create($opts);
  68. $response = file_get_contents($url,false,$context);
  69. return $response;
  70. }
  71. public function onException(\Throwable $throwable)
  72. {
  73. // 捕获 run 方法内所抛出的异常
  74. }
  75. }