class InstanceManager { // ... other methods ... private monitorState(): void { this.instances.forEach((instanceClient) => { const instance = instanceClient.instance; if (!instance) return; if (instance.idleTimeout) { clearInterval(instance.idleTimeout); instance.idleTimeout = null; instance.isIdle = false; instance.idleStart = null; } let count = 0; const max = instanceClient.idleTimeoutDuration / instanceClient.warningInterval; const logMessage = (idleDuration: number, fatal: boolean = false) => { const method = fatal ? instance.logs.fatal : instance.logs.trace; method.call(instance.logs, instanceClient.errors['INSTANCE_MONITOR']({ message: `Instance: ${instance.name}(${instance.id}) has been idle for ${idleDuration / 1000 / 60} minutes.`, details: fatal ? [ `- This instance has been idle for way too long and will now be destroyed to prevent memory leaks/overloads.` ] : [ `- This instance will be destroyed in ${instance.idleTimeoutDuration / 1000 / 60} minutes.`, `- If you wish to keep this instance alive, please perform an operation on it to reset its active state.` ] })); }; const warnAndClose = () => { if (instance.lastUsed) { const currentTime = new Date().getTime(); const lastUsedTime = instance.lastUsed ? instance.lastUsed.getTime() : currentTime; const idleDuration = currentTime - lastUsedTime; if (idleDuration < instance.idleTimeoutDuration) { logMessage(idleDuration); count++; if (count >= max) { logMessage(idleDuration, true); instance.destroy(); } } else { logMessage(idleDuration, true); instance.destroy(); } } }; instance.idleTimeout = setInterval(warnAndClose, instanceClient.warningInterval); }); } }