0

We're running a C# console program as a scheduled task on Windows. This program itself runs a lot of "tasks" that would need to be gracefully shutdown when the program itself is ended.

Is there a way to run cleanup code (that could take a second or two) when the scheduled task is ended? For instance when it is ended by calling Stop-ScheduledTask from a PowerShell script.

I've tried catching CTRL-C events as well as catching the ProcessExit event of AppDomain, but none of these appear to be called when the scheduled task is ended.

As outlined by rrirower in the comments, another option would be to send a signal to the process before asking it to terminate, but this does not seem better supported on Windows.

François Beaune
  • 4,270
  • 7
  • 41
  • 65
  • 2
    Any reason why the script can't run the cleanup code? – rrirower Nov 22 '16 at 16:31
  • It could if there was a way to send a signal to the process, which is another option I'm investigating (no idea how to do that cleanly on Windows, though `taskkill` seems to be one way). – François Beaune Nov 22 '16 at 16:34
  • @Damith Not sure how triggers help here... – François Beaune Nov 22 '16 at 16:45
  • @rrirower One situation that wouldn't work is when the Task is killed before it's finished. You can configure the Task Scheduler to kill a previous instance if it's not finished by the next scheduled start time. –  Nov 22 '16 at 16:55
  • @AndyJ Even that would be fine. _Any_ way to tell the program to gracefully shut down its tasks would be fine. Reliably sending a CTRL-C signal would be one way but that doesn't look doable. One option I've found is to use stdin: http://stackoverflow.com/questions/283128/how-do-i-send-ctrlc-to-a-process-in-c – François Beaune Nov 22 '16 at 16:57

1 Answers1

0

I ended up making an HTTP query to the REST API of the program to ask it to terminate its tasks, right before I terminate the scheduled task:

Invoke-RestMethod -Method Post -Uri ("{0}/Application/TerminateAllTasks" -f $programUrl)
$p = Get-Process "NameOfTheProcess" -ErrorAction Stop
$task | Stop-ScheduledTask -ErrorAction Stop
$p.WaitForExit()

In the longer run, we will convert the program to a proper Windows service, which will make graceful termination easier.

François Beaune
  • 4,270
  • 7
  • 41
  • 65