ElasticSearchGoodsCrontab.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. $page = 1;
  32. while (true) {
  33. $goods = $this->getUpdateGoods($page);
  34. if (!$goods) {
  35. break;
  36. } else {
  37. $page++;
  38. }
  39. foreach($goods as $key=>$value){
  40. $res = $this->http_request(
  41. $welfare_api_set['url'],
  42. ['goodsid'=>$value['id'],'goods_body'=>json_encode($value)]
  43. );
  44. //返回内容写入日志
  45. Logger::getInstance()->notice("商品ID{$value['id']}导入结果:{$res}\n");
  46. }
  47. }
  48. }
  49. //获取30分钟内更新过的商品记录
  50. protected function getUpdateGoods($page = 1)
  51. {
  52. $size = 50;
  53. $offset = ($page - 1) * $size;
  54. $where = ' g.`updatetime`>'.(time()-1800); //30分钟内更新的商品
  55. $que_sql = "SELECT * FROM ims_superdesk_shop_goods g
  56. WHERE {$where}
  57. LIMIT {$offset},{$size}
  58. ";
  59. $queryBuild = new QueryBuilder();
  60. $queryBuild->raw($que_sql);
  61. $res_data = DbManager::getInstance()->query($queryBuild, true, 'default')->toArray();
  62. return $res_data['result'];
  63. }
  64. /**
  65. * http请求
  66. * @param $url 请求地址
  67. * @param $data 数组内容
  68. * @return String 请求返回原生数据
  69. */
  70. protected function http_request($url,$data){
  71. $opts = array(
  72. 'http' => array(
  73. 'method' => 'POST',
  74. 'header' => "Content-type:application/x-www-form-urlencoded",
  75. 'content' => http_build_query($data),
  76. )
  77. );
  78. $context = stream_context_create($opts);
  79. $response = file_get_contents($url,false,$context);
  80. return $response;
  81. }
  82. public function onException(\Throwable $throwable)
  83. {
  84. // 捕获 run 方法内所抛出的异常
  85. }
  86. }