Gracefully Terminate Console App Run Via Task Scheduler

batch-fileconsoletask-schedulerwindows-server-2008

I'm running a console application on Windows Server 2008. I want it to always run, so I have scheduled it to run at startup via the Task Scheduler. I set up the task so it does not require a login.

Now how to stop it? Task Scheduler has an End Task button under All Running Tasks. But that will abruptly stop the task, which I don't want to do. I have programmed it so that CTRL-C will issue a stop request, and it will stop when it's done what it's doing. (For any .NET devs out there I use Console.CancelKeyPress event.)

Is there any way to trigger a cancel key press event (i.e. CTRL-C) in my app when it was run from the Task Scheduler?

(I know one answer is to make it a Windows Service, which I will do eventually, but I need a short term solution.)

Best Answer

In the interim you could make it a service using the srvany utility. it is extremely quick and easy to do. I have found that when the service is stopped, srvany will send a ctrl-c to a console application.

  1. Make a service with srvany and sc:

    sc create myservice binpath= "c:\path to\srvany.exe"

  2. open regedit and find your service at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\

  3. right click and add a key called Parameters

  4. Create a string value called Application and set it with the path to your console app.

That's it.

I don't know if srvany works with 2008 (my googling suggests it does)I have found that, but I know it works fine on 2003. You can get it from the Windows 2003 resource kit.

All you need to do is make scheduled tasks to start and stop the service.