asp.net定時自動執行控制台程式

來源:互聯網
上載者:User

需求是要在一個網站上每隔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檔案,並擷取輸出。

這樣就可以虛擬機器主機上執行自動任務了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.