CollectEquipmentHeartbeatCheckCommand.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Facades\Servers\Logs\Log;
  4. use App\Models\CollectEquipment;
  5. use App\Models\CollectTaskAllocate;
  6. use Illuminate\Console\Command;
  7. class CollectEquipmentHeartbeatCheckCommand extends Command
  8. {
  9. protected $signature = 'collect-equipment-heartbeat-check {--timeout=180}';
  10. protected $description = '巡检设备心跳,超时自动释放设备占用状态';
  11. private const HEARTBEAT_CACHE_PREFIX = 'collect:equipment:heartbeat:';
  12. public function handle()
  13. {
  14. $timeout = (int)$this->option('timeout');
  15. if ($timeout < 60) {
  16. $timeout = 60;
  17. }
  18. if ($timeout > 3600) {
  19. $timeout = 3600;
  20. }
  21. Log::info('collect-equipment-heartbeat-check', '设备心跳巡检开始');
  22. $now = time();
  23. $occupiedEquipmentList = CollectEquipment::query()
  24. ->where('status', '=', 0)
  25. ->where('task_status', '=', 1)
  26. ->select('id')
  27. ->get()
  28. ->toArray();
  29. if (!$occupiedEquipmentList) {
  30. Log::info('collect-equipment-heartbeat-check', '暂无占用设备,巡检结束');
  31. return 0;
  32. }
  33. $releasedNumber = 0;
  34. foreach ($occupiedEquipmentList as $equipment) {
  35. $collectEquipmentId = (int)$equipment['id'];
  36. $heartbeatTime = (int)cache()->get($this->heartbeatCacheKey($collectEquipmentId), 0);
  37. if ($heartbeatTime > 0 && ($now - $heartbeatTime) <= $timeout) {
  38. continue;
  39. }
  40. $releaseRes = CollectEquipment::query()
  41. ->where('id', '=', $collectEquipmentId)
  42. ->where('task_status', '=', 1)
  43. ->update(['task_status' => 0, 'update_time' => $now]);
  44. if (!$releaseRes) {
  45. continue;
  46. }
  47. // 设备中断后,将运行中的子任务置为失败,交给重分配命令处理
  48. CollectTaskAllocate::query()
  49. ->where('collect_equipment_id', '=', $collectEquipmentId)
  50. ->where('status', '=', 1)
  51. ->update(['status' => 4, 'update_time' => $now]);
  52. cache()->forget($this->heartbeatCacheKey($collectEquipmentId));
  53. $releasedNumber++;
  54. }
  55. Log::info('collect-equipment-heartbeat-check', '设备心跳巡检结束,释放设备数量:'.$releasedNumber);
  56. return 0;
  57. }
  58. private function heartbeatCacheKey($collectEquipmentId)
  59. {
  60. return self::HEARTBEAT_CACHE_PREFIX.$collectEquipmentId;
  61. }
  62. }