Run .cmd file every x minutes when app is being used?

I'm trying to find a way to incrementally back-up a folder every 15 minutes, but only if VS Code has been used/in focus since the last time it was backed up.

Does anyone have an idea for how I could do this?


Solution 1:

Relatively easy to do in AutoHotkey... if you have not used it before you may also want to grab SciTE4AutoHotkey which has syntax highlighting.

Here is a rough outline to do something similar... you would have to debug the code to get the window title working properly (use the Window Spy feature from the Tray Icon to get an appropriate WinTitle for VS Code, and see Help description on WinTitle). You would also have to debug the run statement to get it to run a backup... you can run the backup directly or as a batch file, and sometimes it's easier to get a batch file to work.

; Global variable to store last active window time
Global gLastActive 

; This will call the Backup() function periodically..
SetTimer, Backup, % 15*60*1000 ; 15 minutes, in milliseconds

; This is the main loop, just sets a global if the window is active at any point
Loop {
    If WinActive("VS Code") {           ; this will need to be a valid WinTitle
        gLastActive := A_TickCount
        ; MsgBox % "Window detected..."     ; debug message for getting WinTitle correct
    }
    
    Sleep 1000
}

ExitApp         ; Denote logical end of program, will never execute


; Backup function will run periodically and only back things up
;    if VS Code was active since last time...
Backup() {
    Static lastTick
    
    ; If the window was active after the last backup, run a backup this time
    If (gLastActive>lastTick)
        Run, C:\Target.cmd, C:\WorkingDir, Hide ; this will need to be corrected for syntax
    
    lastTick := A_TickCount
}

Note: This is completely untested code, just giving you a framework example to maybe try and start from.