AutoTask.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * @Created by PhpStorm
  4. * @author: Kirin
  5. * @day: 2025/2/19
  6. * @time: 16:58
  7. */
  8. namespace app\command;
  9. use Exception;
  10. use qiniu\services\blockchain\TransactionService;
  11. use Swoole\Coroutine;
  12. use think\console\Command;
  13. use think\console\Input;
  14. use think\console\Output;
  15. use think\facade\Cache;
  16. use think\facade\Log;
  17. class AutoTask extends Command
  18. {
  19. private $task = [
  20. 'test' => ['name' => '测试', 'time' => 300],
  21. ];
  22. protected function configure()
  23. {
  24. // 指令配置
  25. $this->setName('autoTask')
  26. ->setDescription('自动程序');
  27. }
  28. protected function execute(Input $input, Output $output)
  29. {
  30. go(function () {
  31. while (true) {
  32. foreach ($this->task as $k => $v) {
  33. $last_time = Cache::store('redis')->get($k . '_time', 0);
  34. if ($last_time + $v['time'] < time()) {
  35. try {
  36. $this->$k();
  37. $this->log($v['name'] . '执行');
  38. } catch (\Throwable $e) {
  39. Log::error($v['name'] . '运行出错:' . $e->getMessage() . '[' . $e->getFile() . ':' . $e->getLine() . ']');
  40. $this->log($v['name'] . '运行出错:' . $e->getMessage());
  41. }
  42. Cache::store('redis')->set($k . '_time', time());
  43. }
  44. }
  45. Coroutine::sleep(1);
  46. }
  47. });
  48. $output->info("自动程序启动");
  49. }
  50. /**
  51. * @throws Exception
  52. */
  53. private function test()
  54. {
  55. }
  56. public function log($msg)
  57. {
  58. echo "[" . date('Y-m-d H:i:s') . "] " . $msg . PHP_EOL;
  59. }
  60. }