需求是要在一個網站上每隔20分鐘執行自動產生靜態檔案的任務。因為網站是放在購買的虛擬空間的,沒有伺服器的系統管理權限。所以windows服務和自動任務這些方法都是行不通的。我的思路是在網站運行時使用System.Timers.Timer類在後台建立一個線程,來定時執行產生靜態檔案的控制台程式。
首先將控制台程式拷貝到網站的Bin檔案夾中,如static.exe。然後在Global.asax的Application_Start的方法中建立定時執行的任務。Global.asax代碼如下
1 <%@ Application Language="C#" %>
2
3 <%@ Import Namespace="System.Diagnostics" %>
4 <%@ Import Namespace="System.Timers" %>
5
6 <script runat="server">
7 Timer timer;
8
9 void Application_Start(object sender, EventArgs e)
10 { // 每分鐘執行一次控制台程式
11 timer = new System.Timers.Timer(60000);
12 timer.Elapsed += new ElapsedEventHandler(ExeConsole);
13 timer.Start();
14 }
15
16 void Application_End(object sender, EventArgs e)
17 {
18 if(timer != null)
19 {
20 timer.Stop();
21 timer.Close();
22 }
23
24 }
25
26 void Application_Error(object sender, EventArgs e)
27 {
28 // 在出現未處理的錯誤時啟動並執行代碼
29
30 }
31
32 void Session_Start(object sender, EventArgs e)
33 {
34 // 在新會話啟動時啟動並執行代碼
35
36 }
37
38 void Session_End(object sender, EventArgs e)
39 {
40 // 在會話結束時啟動並執行代碼。
41 // 注意: 只有在 Web.config 檔案中的 sessionstate 模式設定為
42 // InProc 時,才會引發 Session_End 事件。如果會話模式設定為 StateServer
43 // 或 SQLServer,則不會引發該事件。
44
45 }
46
47
48 private static void ExeConsole(object sender, System.Timers.ElapsedEventArgs e)
49 {
50 string path = @"D:\AspNetAutoTask\Bin\static.exe";
51 string cmd = path + @" D:\AspNetAutoTask\";
52
53 Process process = new System.Diagnostics.Process();
54 ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe");
55 startInfo.UseShellExecute = false;
56 startInfo.RedirectStandardInput = true;
57 startInfo.RedirectStandardOutput = true;
58 process.StartInfo = startInfo;
59 process.Start();
60
61 process.StandardInput.WriteLine(cmd);
62 process.StandardInput.WriteLine("exit");
63 }
64
65 </script>
ExeConsole是在asp.net中執行控制台程式的方法,相關參考見C#在單獨進程中運行.exe檔案,並擷取輸出。
這樣就可以虛擬機器主機上執行自動任務了。