现在的位置: 首页 > 综合 > 正文

asp.net定时自动执行控制台程序

2013年01月28日 ⁄ 综合 ⁄ 共 2107字 ⁄ 字号 评论关闭

需求是要在一个网站上每隔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文件,并获取输出

这样就可以虚拟主机上执行自动任务了。

抱歉!评论已关闭.