1. 程式人生 > >定時任務-C#線程類 windows服務

定時任務-C#線程類 windows服務

system 由於 star pri code windows 方法的參數 方法 html

原理

最常用的就是C#中 timer類寫一個定時方法,然後在把他宿主到windows服務裏面。

C#中Timer分類

關於C# Timer類 在C#裏關於定時器類就有3個

C# Timer使用的方法1.定義在System.Windows.Forms裏

C# Timer使用的方法2.定義在System.Threading.Timer類裏 "

C# Timer使用的方法3.定義在System.Timers.Timer類裏

◆System.Windows.Forms.Timer

應用於WinForm中的,它是通過Windows消息機制實現的,類似於VB或Delphi中的Timer控件,內部使用API SetTimer實現的。它的主要缺點是計時不精確,而且必須有消息循環,Console Application(控制臺應用程序)無法使用。

◆System.Timers.Timer

和System.Threading.Timer非常類似,它們是通過.NET Thread Pool實現的,輕量,計時精確,對應用程序、消息沒有特別的要求。

◆System.Timers.Timer還可以應用於WinForm,完全取代上面的Timer控件。它們的缺點是不支持直接的拖放,需要手工編碼。

System.Threading.Timer

技術分享圖片
public class BizCommon
{
    /// <summary>
    ////// </summary>
    public static object LockObject = new object
(); public static void StartTime() { //第二個參數是回調方法的參數 Timer t = new Timer(StartBiz, null, 0, 5000); //t.Change(0, 5000); } private static void StartBiz(object o) { if (Monitor.TryEnter(LockObject)) { FileStream fs = new FileStream("C:\\log.txt
", FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(fs); sw.WriteLine("Time:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); sw.Close(); } } }
View Code

System.Timers.Timer

技術分享圖片
public class BizCommon
{
    /// <summary>
    ////// </summary>
    public static object LockObject = new object();

    public static void StartTime()
    {
        System.Timers.Timer tm = new System.Timers.Timer();
        tm.Interval = 5000;
        tm.Elapsed += new System.Timers.ElapsedEventHandler(StartBiz);
        tm.AutoReset = true; //執行一次false,一直循環執行true
        tm.Enabled = true;//是否執行Elapsed事件。
        tm.Start();
        //tm.Stop();
    }
    private static void StartBiz(object sender, System.Timers.ElapsedEventArgs e)
    {
        if (Monitor.TryEnter(LockObject))
        {
            FileStream fs = new FileStream("C:\\log.txt", FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine("Time:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"));
            sw.Close();
        }
    }
}
View Code

更多關於多線程的教程請看

http://www.cnblogs.com/wudequn/category/1154929.html

技術分享圖片
public static void StartTime()
{
    System.Timers.Timer tm = new System.Timers.Timer();
    tm.Interval = 1000;
    tm.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
    tm.Start();

}
private static void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    int intHour = e.SignalTime.Hour;
    int intMinute = e.SignalTime.Minute;
    int intSecond = e.SignalTime.Second;
    // 設置 每天 00:00:00開始執行程序  
    //
    //由於計算機性能問題,有時候可能會跳過某一秒,導致沒有執行。  這種導致任務沒有處理的異常叫做missfire
    //這種就要做很多處理,其他時間段在查看數據庫是否今天這個時間處理過。沒有處理在重新處理等等 補償操作。
    if (intHour == 00 && intMinute == 00 && intSecond == 00)
    {
        //do something
    }
}
特定時間點處理任務
Windows服務
技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

創建過程

技術分享圖片

下載項目

技術分享圖片編譯完之後,裏面有安裝 和 寫在 windows服務的批處理文件。

定時任務-C#線程類 windows服務