简体   繁体   English

计划的任务终止时如何运行代码

[英]How to run code when a scheduled task is terminated

We're running a C# console program as a scheduled task on Windows. 我们正在Windows上按计划任务运行C#控制台程序。 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. 例如,通过从PowerShell脚本调用Stop-ScheduledTask结束该操作时。

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. 我尝试捕获CTRL-C事件以及AppDomainProcessExit事件,但是在计划任务结束时,似乎都没有调用这些事件。

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. 正如rrirower在评论中所概述的那样 ,另一种选择是在请求终止之前向该进程发送信号,但这似乎在Windows上并不更好。

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: 我最终在终止计划的任务之前,对程序的REST API进行了HTTP查询,要求其终止其任务:

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. 从长远来看,我们会将程序转换为适当的Windows服务,这将使终止终止变得更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM