如何在计划任务终止时运行代码 [英] How to run code when a scheduled task is terminated
问题描述
我们在 Windows 上将 C# 控制台程序作为计划任务运行.这个程序本身运行了很多任务",需要在程序本身结束时正常关闭.
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.
有没有办法在计划任务结束时运行清理代码(可能需要一两秒钟)?例如,当它通过从 PowerShell 脚本调用 Stop-ScheduledTask
结束时.
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.
我已经尝试捕获 CTRL-C 事件以及捕获 AppDomain
的 ProcessExit
事件,但是在计划任务结束时这些似乎都没有被调用.
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.
正如 rrirower 在评论中所概述的,另一种选择是在要求进程终止之前向进程发送信号,但这在 Windows 上似乎并没有得到更好的支持.
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.
推荐答案
我最终对程序的 REST API 进行了 HTTP 查询,要求它在我终止计划任务之前终止其任务:
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()
从长远来看,我们会将程序转换为适当的 Windows 服务,这将使优雅终止更容易.
In the longer run, we will convert the program to a proper Windows service, which will make graceful termination easier.
这篇关于如何在计划任务终止时运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!