Api.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Spider\Lib;
  3. use Dever;
  4. class Api
  5. {
  6. private $queue;
  7. public function run($id)
  8. {
  9. # 写入队列
  10. $project = new Project($id);
  11. $config = $project->get();
  12. if (!$this->queue) {
  13. $this->queue = new Queue('db');
  14. }
  15. $send['id'] = $config['id'];
  16. $send['collect_rule'] = $config['collect_rule'];
  17. foreach ($config['url'] as $k => $v) {
  18. $this->queue->push($v, $send, $config['page_num']);
  19. }
  20. }
  21. public function test_api($id)
  22. {
  23. Dever::setInput('test', 1);
  24. $this->queue = new Queue('data');
  25. $this->run($id);
  26. $this->cron();
  27. return 'yes';
  28. }
  29. private function cron()
  30. {
  31. if (!$this->queue) {
  32. $this->queue = new Queue('db');
  33. }
  34. Dever::import('task');
  35. $state = true;
  36. while ($state) {
  37. $state = $this->load();
  38. }
  39. }
  40. private function load()
  41. {
  42. $config = $this->queue->pop();
  43. if ($config) {
  44. # 此处开task
  45. Dever::task(function() use($config, $this)
  46. {
  47. $col = $this->col($config['id']);
  48. $this->parse($config['url'], $config['id'], $config['collect_rule'], $col);
  49. });
  50. $state = true;
  51. } else {
  52. $state = false;
  53. }
  54. return $state;
  55. }
  56. private function col($project)
  57. {
  58. return Dever::db('spider/col')->getList(['where_project_id' => $project]);
  59. }
  60. private function parse($url, $project, $rule, $col)
  61. {
  62. $parse = new Parse($url, $project, $rule, $col);
  63. return $parse->get();
  64. }
  65. }