在Global.asax中设置Asp.Net的定时任务

服务器端采用C#语法:
1.在Global.asax文件中导入命名空间
<%@ Import Namespace="System.Timers" %>

2.Global.asax文件中的Application_Start()方法内写如下代码:
System.Timers.Timer objTimer = new Timer();
objTimer.Interval = 时间; //这个时间单位毫秒,比如10秒,就写10000
objTimer.Enabled = true;
objTimer.Elapsed += new ElapsedEventHandler(objTimer_Elapsed);

3.Global.asax文件中添加一个方法
void objTimer_Elapsed(object sender, ElapsedEventArgs e)
{
//这个方法内实现你想做的事情。
//例如:修改Application的某一个值等等。
}
以上3步则可以在指定时间间隔执行这个objTimer_Elapsed()方法,即达到你要得效果


  1. using System;
  2. using System.Timers;
  3. namespace 定时器ConsoleApplication1
  4. {
  5. class Class1
  6. { 
  7.  [STAThread] 
  8.  static void Main(string[] args)
  9.  {
  10.   System.Timers.Timer aTimer = new System.Timers.Timer();
  11.   aTimer.Elapsed += new ElapsedEventHandler(TimeEvent);
  12.   // 设置引发时间的时间间隔 此处设置为1秒(1000毫秒)
  13.   aTimer.Interval = 1000;
  14.   aTimer.Enabled = true;
  15.   Console.WriteLine("按回车键结束程序");
  16.   Console.WriteLine(" 等待程序的执行......");
  17.   Console.ReadLine();
  18.  }
  19.  // 当时间发生的时候需要进行的逻辑处理等
  20. //  在这里仅仅是一种方式,可以实现这样的方式很多.
  21. private static void TimeEvent(object source, ElapsedEventArgs e)
  22.  {  
  23.   // 得到 hour minute second 如果等于某个值就开始执行某个程序。
  24.   int intHour  = e.SignalTime.Hour;
  25.   int intMinute = e.SignalTime.Minute;
  26.   int intSecond = e.SignalTime.Second;
  27.   // 定制时间; 比如 在10:30 :00 的时候执行某个函数
  28.   int iHour  = 10;
  29.   int iMinute = 30;
  30.   int iSecond = 00;
  31.   // 设置  每秒钟的开始执行一次
  32.   if( intSecond == iSecond )
  33.   {
  34.   Console.WriteLine("每秒钟的开始执行一次!");
  35.   }
  36.   // 设置 每个小时的30分钟开始执行
  37.   if( intMinute == iMinute && intSecond == iSecond )
  38.   {
  39.   Console.WriteLine("每个小时的30分钟开始执行一次!");
  40.   }
  41.  // 设置 每天的10:30:00开始执行程序
  42.   if( intHour == iHour && intMinute == iMinute && intSecond == iSecond )
  43.   {
  44.   Console.WriteLine("在每天10点30分开始执行!");
  45.   }
  46.  }
  47. }
  48. }



转载于:https://www.cnblogs.com/meguoling/archive/2012/08/03/2621627.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值