安装程序中的Vista计划任务

我正在使用Visual Studio 2008中的安装向导项目部署C#应用程序。

对于我来说,让Windows安排我的应用程序定期运行(例如每8小时),最简单的方法是什么? 我更喜欢在应用程序安装期间进行此调度以简化最终用户的设置。

谢谢!

计划任务是您的最佳选择。 请查看此页面,了解如何使用脚本设置任务。

这需要为我整理一些,所以这里是完整的文档,用于从安装项目安排任务。

创建部署项目后,您将需要使用自定义操作来安排任务。 演练:创建自定义操作

注意:演练要求您将主输出添加到“安装”节点,即使您不打算在“安装”步骤期间执行任何自定义操作。 这很重要,所以不要像我一样忽略它。 安装程序类在此步骤中执行一些状态管理,并且需要运行。

下一步是将安装目录传递给自定义操作。 这是通过CustomActionData属性完成的。 我为提交节点输入了/DIR="[TARGETDIR]\" (我在提交步骤中安排了我的任务)。 MSDN:CustomActionData属性

最后,您需要访问任务调度API,或使用Process.Start调用schtasks.exe 。 API将为您提供更加无缝和强大的体验,但我选择了schtasks路由,因为我有方便的命令行。

这是我最终得到的代码。 我将其注册为安装,提交和卸载的自定义操作。

 using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration.Install; using System.Linq; using System.Security.Permissions; using System.Diagnostics; using System.IO; namespace MyApp { [RunInstaller(true)] public partial class ScheduleTask : System.Configuration.Install.Installer { public ScheduleTask() { InitializeComponent(); } [SecurityPermission(SecurityAction.Demand)] public override void Commit(IDictionary savedState) { base.Commit(savedState); RemoveScheduledTask(); string installationPath = Context.Parameters["DIR"] ?? ""; //Without the replace, results in c:\path\\MyApp.exe string executablePath = Path.Combine(installationPath, "MyApp.exe").Replace("\\\\", "\\"); Process scheduler = Process.Start("schtasks.exe",string.Format("/Create /RU SYSTEM /SC HOURLY /MO 2 /TN \"MyApp\" /TR \"\\\"{0}\\\"\" /st 00:00", executablePath)); scheduler.WaitForExit(); } [SecurityPermission(SecurityAction.Demand)] public override void Uninstall(IDictionary savedState) { base.Uninstall(savedState); RemoveScheduledTask(); } private void RemoveScheduledTask() { Process scheduler = Process.Start("schtasks.exe", "/Delete /TN \"MyApp\" /F"); scheduler.WaitForExit(); } } }