1、在項目開發的中,經常會遇到要定時執行的任務,今天我們寫一個在Global.asax.cs程序中的定時任務寫法。
因為項目執行是從Application_Start() 方法開始的,所以我們寫定時任務,需要將定時計划在這個方法中定義。
將下面代碼放在Application_Start() 方法的最后面。
1 #region 預警消息推送定時-5分鍾一次 2 3 int TimerS = 5 * 60 * 1000; 4 5 System.Timers.Timer tm = new System.Timers.Timer(TimerS); 6 tm.Elapsed += tm_Elapsed; 7 tm.AutoReset = true; 8 tm.Enabled = true; 9 #endregion
在Global.asax.cs新建一個定時任務的方法,如下所示
//定時執行推送 private void tm_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { SearchModuleBLL service = new SearchModuleBLL(); service.PushSKMessages(); }