Question

We have scheduled a Windows Task to kick off some custom code (as an executable) that checks for existence of a file every 15 minutes.

If the file is eventually found, our service does some processing on it. Here's the rub: after the file is processed, the business requires that Task Scheduler stops these 15-minute checks until the next day.

Is there a way to insert logic into Windows Task Scheduler to stop running its trigger once some condition is met? Or is there a better way to architect this process?

We are using Windows Server 2008 R2 Standard SP1 to run this.

Was it helpful?

Solution

How to end a scheduled task:

A. To terminate a currently running task (i.e. one that shows up in Task Scheduler -> "Display All Running Tasks) from the command line:
schtasks.exe /End /TN "My task name"

B. To stop a scheduled task from being triggered to run in the future:
schtasks.exe /Change /TN "My task name" /DISABLE

C. To re-enable the task:
schtasks.exe /Change /TN "My task name" /ENABLE

More details are available by typing: schtasks.exe /Change /?

D. To ask a process to terminate (here: Notepad, but use the name displayed in Task Manager -> Processes\Image Name) that does not terminate when you run A. above:
taskkill.exe /IM Notepad.exe

E. To forcefully terminate a process that does not terminate when you run D. above:
taskkill.exe /F /IM Notepad.exe /T

Note: Using taskkill isn't a clean way of ending a process. You can read more in this post and in the article it links to.


How to set this up in Task Scheduler for your described situation:

Instead of having your task run the custom .exe directly, change it to run a script (e.g. a batch file, PowerShell script, Python script, etc.) which in turn:

  • Triggers the custom exe, then
  • Tests whether the file was found and "processed", then
  • Invokes command B. above to stop it from running again.

Add a second task that runs every morning (check "Run whether user is logged on or not) that re-enables the scheduled task by invoking command C. above.

Note: To invoke schtasks.exe requires elevated privileges, so set the task that executes that command to "Run with highest privileges".


How to detect that the file has been processed:

  • Have your custom .exe to add a Registry entry when it ran successfully. Your script can look for that entry using e.g. reg.exe (type REG QUERY /? for details).

There are other ways (e.g. posting a Windows event, sending a message, etc.), but using the Registry is an easy mechanism for a simple script to use.

Don't disable the task from directly your .exe. Keep the application and its invocation separate. That will also save you from having to recompile if you want to disable the task differently later.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top