Batch: How to run a program when the computer is idle and stop when it's used?

I need to run a Windows batch (or any other command line software would do fine) that would run a program when the computer has been idle for a minute and stop it when it's used. I should obviously start it back again when it's idle again.

Any ideas? Couldn't find anything that doesn't use GUI.


This is a perfect job for AutoIt: http://autoitscript.com

Here's a script I threw together for you. Put it in an .au3 file, replace notepad with your exe, and for Run, include the full path:

#include <Timers.au3>
While 1
   Sleep(10)
   $idleTimer = _Timer_GetIdleTime()
   If $idleTimer > 60000 And Not ProcessExists("notepad.exe") Then
      Run("notepad.exe")
   ElseIf $idleTimer < 10 Then
      ProcessClose("notepad.exe")
   EndIf
WEnd

If you don't want to use AutoIt then look into the quser command which displays, amongst other things, the idle time to the nearest minute:

C:\Users\Richard>quser
 USERNAME              SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>richard               console             1  Active      none   26/06/2014 15:29
C:\Users\Richard>

One simple way would be to test the output of:

quser | findstr /I %USERNAME% | findstr "none"

and if it comes back empty, then they are over 1 minute idle.