1. 程式人生 > >C#定時 器 定時執行任務 執行緒

C#定時 器 定時執行任務 執行緒

http://www.cnblogs.com/linzheng/archive/2011/02/21/1960276.html

C#實現Web應用程式定時啟動任務

     在業務複雜的應用程式中,有時候會要求一個或者多個任務在一定的時間或者一定的時間間隔內計劃進行,比如定時備份或同步資料庫,定時傳送電子郵件等,我們稱之為計劃任務。實現計劃任務的方法也有很多,可以採用SQLAgent執行儲存過程來實現,也可以採用Windows任務排程程式來實現,也可以使用Windows服務來完成我們的計劃任務,這些方法都是很好的解決方案。但是,對於Web應用程式來說,這些方法實現起來並不是很簡單的,主機服務提供商或者不能直接提供這樣的服務,或者需要你支付許多額外的費用。 本文就介紹一個直接在Web應用程式中使用的簡單的方法,這個方法不需要任何額外的配置即可輕鬆實現。

由於ASP.NET站點是作為Web應用程式執行的,它並不受執行緒的限制,因此我們可以非常方便地在Application_Start和Application_End事件中建立和銷燬一個計劃任務。

ASP.NET   框架應用程式在第一次向伺服器發出請求時建立,在此之前,不執行   ASP.NET   程式碼。當第一個請求發出後,將建立一個   HttpApplication   例項池並引發   Application_Start   事件。
HttpApplication   例項處理該請求以及後面的請求,直到最後一個例項退出並引發   Application_End   事件。

IIS應用池回收造成Application_Start中定時執行程式停止的問題的解決方法

原理就是在應用程式結束時發出一個Web請求訪問網站,啟動Application_Start。

複製程式碼
void Application_End(object sender, EventArgs e)
{
// 在應用程式關閉時執行的程式碼
//解決應用池回收問題
System.Threading.Thread.Sleep(5000);
string strUrl = "網站地址";
System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strUrl);
System.Net.HttpWebResponse _HttpWebResponse = (System.Net.HttpWebResponse)_HttpWebRequest.GetResponse();
System.IO.Stream _Stream = _HttpWebResponse.GetResponseStream();//得到回寫的位元組流
}
複製程式碼
下面就簡單介紹一下在Web站點實現計劃任務的方法。我們的例子是定時往檔案裡新增資訊,作為例子,這裡把當前的時間定時地寫入檔案中。

一個計劃任務的工作單元稱之為一個任務(Job),下面的程式碼描述了對所有任務都可以被排程引擎計劃執行的一個通用的介面,這裡的每個任務實現了Execute方法,供排程引擎進行呼叫:

public interface ISchedulerJob
{
void Execute();
}

如前所述,我們的例子是實現往檔案寫如字元日期,下面就是實現這一任務的方法:

複製程式碼
public class SampleJob : ISchedulerJob
{
public void Execute()
{
//檔案儲存的物理路徑,CSTest為虛擬目錄名稱,F:\Inetpub\wwwroot\CSTest為物理路徑
string p = @"F:\Inetpub\wwwroot\CSTest";
//我們在虛擬目錄的根目錄下建立SchedulerJob資料夾,並設定許可權為匿名可修改,
//SchedulerJob.txt就是我們所寫的檔案
string FILE_NAME = p+ "\\SchedulerJob\\SchedulerJob.txt";
//取得當前伺服器時間,並轉換成字串
string c = System.DateTime.Now.ToString("yyyy-mm-dd hh:MM:ss");
//標記是否是新建檔案的標量
bool flag = false;
//如果檔案不存在,就新建該檔案
if (!File.Exists(FILE_NAME))
{
flag = true;
StreamWriter sr = File.CreateText(FILE_NAME);
sr.Close();
}
//向檔案寫入內容
StreamWriter x = new StreamWriter(FILE_NAME,true,System.Text.Encoding.Default);
if(flag) x.Write("計劃任務測試開始:");
x.Write("\r\n"+c);
x.Close();
}
}
複製程式碼

接下來,我們建立一個配置物件,告訴排程引擎執行什麼任務和執行的時間間隔。

複製程式碼
public class SchedulerConfiguration
{
//時間間隔
private int sleepInterval;
//任務列表
private ArrayList jobs = new ArrayList();

public int SleepInterval { get { return sleepInterval; } }
public ArrayList Jobs { get { return jobs; } }

//排程配置類的建構函式
public SchedulerConfiguration(int newSleepInterval)
{
sleepInterval = newSleepInterval;
}
}
複製程式碼

下面就是排程引擎,定時執行配置物件的任務

複製程式碼
public class Scheduler
{
private SchedulerConfiguration configuration = null;

public Scheduler(SchedulerConfiguration config)
{
configuration = config;
}

public void Start()
{
while(true)
{
//執行每一個任務
foreach(ISchedulerJob job in configuration.Jobs)
{
ThreadStart myThreadDelegate = new ThreadStart(job.Execute);
Thread myThread = new Thread(myThreadDelegate);
myThread.Start();
Thread.Sleep(configuration.SleepInterval);
}
}
}
}
複製程式碼


所有的準備工作已經完成,下面就是啟用引擎的工作了。為了讓我們的任務計劃執行,我們在Global.asax.cs檔案裡的Applicatio_Start和Application_End裡進行建立和銷燬工作,首先建立一個排程程序執行的執行緒,我們這裡的執行間隔時間為3秒鐘。

複製程式碼
public System.Threading.Thread schedulerThread = null;
protected void Application_Start(Object sender, EventArgs e)
{
SchedulerConfiguration config = new SchedulerConfiguration(1000*3);
config.Jobs.Add(new SampleJob());
Scheduler scheduler = new Scheduler(config);
System.Threading.ThreadStart myThreadStart = new System.Threading.ThreadStart(scheduler.Start);
System.Threading.Thread schedulerThread = new System.Threading.Thread(myThreadStart);
schedulerThread.Start();
}
複製程式碼

最後還需要在程式退出時進行銷燬:

複製程式碼
protected void Application_End(Object sender, EventArgs e)
{
if (null != schedulerThread)
{
schedulerThread.Abort();
}
}
複製程式碼

好了,在VS.NET裡建立一個C#的Web應用程式工程,建立TaskScheduler.cs類,並修改相應的Global.asax.cs檔案。為了能看到效果,我們再建立一個表單WebForm1.aspx,定時重新整理來檢查我們所記錄的資料:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
Inherits="CSTest.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>在Web應用程式中執行計劃任務的例子</title>
<meta http-equiv="refresh" content="10">
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<iframe style="width:100%;height:100%" src="/SchedulerJob/SchedulerJob.txt"></iframe>
</form>
</body>
</HTML>

標籤: .NET

 class Program
    {
        private static System.Timers.Timer aTimer;

        static void Main(string[] args)
        {
            SetTimer();

            Console.WriteLine("\nPress the Enter key to exit the application...\n");
            Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
            Console.ReadLine();
            aTimer.Stop();
            aTimer.Dispose();

            Console.WriteLine("Terminating the application...");
        }
        private static void SetTimer()
        {
            // Create a timer with a two second interval.
            aTimer = new System.Timers.Timer(2000);
            // Hook up the Elapsed event for the timer.
            aTimer.Elapsed += OnTimedEvent;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;
        }

        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            if (e.SignalTime.Minute == 49&&(e.SignalTime.Second==1||e.SignalTime.Second==2))
            {
                Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                              e.SignalTime.Minute);
            }
            
        }
    }