.net利用Timer和Global.asax实现定时执行程序C#

TestTimer.cs代码:
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Threading;
 6 
 7 namespace Model
 8 {
 9     public class TestTimer
10     {
11         //定义变量n,Timer执行一次n自动加一,根据n来控制定时执行的时间,来解决Timer只能定时一分钟的时间范围
12         static int n = 0;
13         //TimerCallback 委托,GlobalTimer_ToDo表示要执行的方法
14         public static Timer GlobalTimer = new Timer(new TimerCallback(GlobalTimer_ToDo), null, Timeout.Infinite, Timeout.Infinite);
15 
16         /*也可以直接定时
17         GlobalTimer.Interval = 10;
18                 GlobalTimer.Enabled = true;
19                 GlobalTimerAutoReset = true;*/
20 
21         static void GlobalTimer_ToDo(object obj)
22         {
23             n = n + 1;
24             if (n == 2)
25             {
26                 //***这里写你要定时执行的程序
27 
28                 n = 0;
29             }
30         }
31 
32         public static void Start(long a, long b)
33         {
34             //Timer.Change(Int32, Int32)方法用来更改计时器的启动时间和方法调用之间的间隔,用 32 位有符号整数度量时间间隔
35             GlobalTimer.Change(a, b);
36         }
37 
38         public static void Stop()
39         {
40             //Timeout.Infinite是用于指定无限长等待时间的常数
41             GlobalTimer.Change(Timeout.Infinite, Timeout.Infinite);
42         }
43     }

44 } 

Global.asax.cs代码: 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Security;
 6 using System.Web.SessionState;
 7 
 8 namespace Model
 9 {
10     public class Global : System.Web.HttpApplication
11     {
12 
13         protected void Application_Start(object sender, EventArgs e)
14         {
15             //参数0表示立即执行定时器,60000单位毫秒,就是一分钟执行一次
16             TestTimer.Start(06000);
17         }
18 
19         protected void Session_Start(object sender, EventArgs e)
20         {
21 
22         }
23 
24         protected void Application_BeginRequest(object sender, EventArgs e)
25         {
26 
27         }
28 
29         protected void Application_AuthenticateRequest(object sender, EventArgs e)
30         {
31 
32         }
33 
34         protected void Application_Error(object sender, EventArgs e)
35         {
36 
37         }
38 
39         protected void Session_End(object sender, EventArgs e)
40         {
41 
42         }
43 
44         protected void Application_End(object sender, EventArgs e)
45         {
46 
47         }
48     }

49 }

停止定时器调用TestTimer.Stop();释放定时器调用TestTimer.GlobalTimer.Dispose(); 

posted on 2012-01-13 17:48  NetPig  阅读(1628)  评论(0编辑  收藏  举报

导航