node.jselectronnode-webkitnwjs

How to check when the computer is idle in NodeJS?


I want to run a process in the background in NodeJS, that wait until the computer not in use for 10 minutes. I mean the user do not touch the keyboard or the mouse.

In other words: I want to listen to keyboard and mouse events in any window, and notify my app when it is happend.

For this mission, I able to use plain node, or nw.js or electron.

I think that I must to use a C++, native module and DLL's. But I hope there is a better and simple solution.

Do you have?


Solution

  • Since nodejs v11.10, you can use monitorEventLoopDelay api to do it.

    const { monitorEventLoopDelay } = require('node:perf_hooks');
    
    // Monitor event loop delay
    const monitor = monitorEventLoopDelay({ resolution: 10 });
    monitor.enable();
    
    // Tasks to execute when idle is detected
    function runIdleTasks() {
      console.log('The event loop is idle, executing tasks...');
      // Execute your idle-time logic here
    }
    
    // Periodically check the event loop status
    setInterval(() => {
      // Get event loop delay (in milliseconds)
      const delay = monitor.mean / 1000000;
      
      // If the delay is very low, it means the event loop is relatively idle
      if (delay < 5) { // The threshold can be adjusted according to actual conditions
        runIdleTasks();
      }
    }, 1000); // Check once per second