5

我在Visual Studio中使用安装向导项目部署C#应用程序2008Vista的计划任务从安装

什么是我让Windows安排我的应用程序定期运行的最简单的方法(例如每8小时)?我更喜欢在应用程序安装过程中是否发生这种安排,以简化最终用户的设置。

谢谢!

回答

0

计划任务是你要走的路。查看此页面,了解如何使用script设置任务。

+0

然后,我必须将该脚本与安装程序绑定在一起,并在安排其他程序运行后将其删除。有没有一种方法可以让安装向导为我做这件事? – mrduclaw 2009-11-21 08:35:08

+0

您可以在设置组件中执行任何可以在脚本中执行的操作。 – rerun 2009-11-21 21:38:48

10

这花了一些时间对我来说,所以这里有完整的文档来安排安装项目的任务。

一旦您创建了部署项目,您将需要使用Custom Actions来安排任务。 Walkthrough: Creating a Custom Action

注:的演练要求您添加主输出到安装节点,即使你不安装过程中的步骤定制做任何计划。 这很重要,所以不要像我那样忽略它。安装程序类在此步骤中执行一些状态管理,并且需要运行。

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

最后,您需要访问任务计划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(); 
     } 
    } 
} 
+0

得分!很好的答案,保存了我一天的一半;-) – 2011-10-25 23:00:25