web網站里面,需要每隔1分鍾,執行一個任務,並且一直保持這個定時執行狀態,可以用如下一個方法:
1,Global.asax里面的 Application_Start ,發生在第一次請求網站的時候,網站關閉(iis關閉網站或者刪除網站)
在寫這個Application_Start 里面的內容之前,先寫個定時器:

public class Time_Task { public event System.Timers.ElapsedEventHandler ExecuteTask; private static readonly Time_Task _task = null; private System.Timers.Timer _timer = null; //定義時間 private int _interval = 1000; public int Interval { set { _interval = value; } get { return _interval; } } static Time_Task() { _task = new Time_Task(); } public static Time_Task Instance() { return _task; } //開始 public void Start() { if (_timer == null) { _timer = new System.Timers.Timer(_interval); _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed); _timer.Enabled = true; _timer.Start(); } } protected void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (null != ExecuteTask) { ExecuteTask(sender, e); } } //停止 public void Stop() { if (_timer != null) { _timer.Stop(); _timer.Dispose(); _timer = null; } } }
2,然后,再寫Global.asax

public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { // 在應用程序啟動時運行的代碼 Time_Task.Instance().ExecuteTask += new System.Timers.ElapsedEventHandler(Global_ExecuteTask); Time_Task.Instance().Interval = 1000*10;//表示間隔 Time_Task.Instance().Start(); } void Global_ExecuteTask(object sender, System.Timers.ElapsedEventArgs e) { //在這里編寫需要定時執行的邏輯代碼 } protected void Session_Start(object sender, EventArgs e) { // 在新會話啟動時運行的代碼 } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { // 在出現未處理的錯誤時運行的代碼 } protected void Session_End(object sender, EventArgs e) { // 在會話結束時運行的代碼 // 注意: 只有在 Web.config 文件中的 sessionstate 模式設置為 // InProc 時,才會引發 Session_End 事件。如果會話模式設置為 StateServer // 或 SQLServer,則不會引發該事件 } protected void Application_End(object sender, EventArgs e) { // 在應用程序關閉時運行的代碼 } }
然后,只要第一次訪問網站,就會每隔 10秒(自己定義) 執行定義的任務,可以在要執行的任務里面設置斷點,然后調試...