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