| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- namespace App\Console\Commands;
- use App\Facades\Servers\Logs\Log;
- use App\Models\CollectEquipment;
- use App\Models\CollectTaskAllocate;
- use Illuminate\Console\Command;
- class CollectEquipmentHeartbeatCheckCommand extends Command
- {
- protected $signature = 'collect-equipment-heartbeat-check {--timeout=180}';
- protected $description = '巡检设备心跳,超时自动释放设备占用状态';
- private const HEARTBEAT_CACHE_PREFIX = 'collect:equipment:heartbeat:';
- public function handle()
- {
- $timeout = (int)$this->option('timeout');
- if ($timeout < 60) {
- $timeout = 60;
- }
- if ($timeout > 3600) {
- $timeout = 3600;
- }
- Log::info('collect-equipment-heartbeat-check', '设备心跳巡检开始');
- $now = time();
- $occupiedEquipmentList = CollectEquipment::query()
- ->where('status', '=', 0)
- ->where('task_status', '=', 1)
- ->select('id')
- ->get()
- ->toArray();
- if (!$occupiedEquipmentList) {
- Log::info('collect-equipment-heartbeat-check', '暂无占用设备,巡检结束');
- return 0;
- }
- $releasedNumber = 0;
- foreach ($occupiedEquipmentList as $equipment) {
- $collectEquipmentId = (int)$equipment['id'];
- $heartbeatTime = (int)cache()->get($this->heartbeatCacheKey($collectEquipmentId), 0);
- if ($heartbeatTime > 0 && ($now - $heartbeatTime) <= $timeout) {
- continue;
- }
- $releaseRes = CollectEquipment::query()
- ->where('id', '=', $collectEquipmentId)
- ->where('task_status', '=', 1)
- ->update(['task_status' => 0, 'update_time' => $now]);
- if (!$releaseRes) {
- continue;
- }
- // 设备中断后,将运行中的子任务置为失败,交给重分配命令处理
- CollectTaskAllocate::query()
- ->where('collect_equipment_id', '=', $collectEquipmentId)
- ->where('status', '=', 1)
- ->update(['status' => 4, 'update_time' => $now]);
- cache()->forget($this->heartbeatCacheKey($collectEquipmentId));
- $releasedNumber++;
- }
- Log::info('collect-equipment-heartbeat-check', '设备心跳巡检结束,释放设备数量:'.$releasedNumber);
- return 0;
- }
- private function heartbeatCacheKey($collectEquipmentId)
- {
- return self::HEARTBEAT_CACHE_PREFIX.$collectEquipmentId;
- }
- }
|