天天看點

C# .net 定時器,多線程實作定時器

用多線程實作定時器的功能

利用了Thread Sleep

寫了個死循環

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;
using System.Security.Cryptography;

namespace TestConsoleApplication
{
    class Program
    {
        /// <summary>  
        /// 聲明一個線程執行個體  
        /// </summary>  
        public static Thread mythread;

        #region 計算剩餘時間
        private static int CompareDate(string synchroDateStr)
        {
            long nowDT = DateTime.Now.Ticks/10000;
            DateTime synchroDate = Convert.ToDateTime(synchroDateStr);
            long synchroDT = synchroDate.Ticks/10000;
            Console.WriteLine("目前時間的毫秒數:" + nowDT);
            Console.WriteLine("執行同步的時間的毫秒數:" + synchroDT);
            int sleepDT = 0;
            if (synchroDT > nowDT) {
                sleepDT = Convert.ToInt32(synchroDT - nowDT);
            }

            Console.WriteLine("剩餘時間的秒數:" + sleepDT);
            Console.WriteLine("剩餘時間的毫秒數:" + sleepDT / 1000);
            Console.WriteLine("剩餘時間的分鐘數:" + sleepDT / 1000 / 60);
            Console.WriteLine("剩餘時間的小時數:" + sleepDT / 1000/60/60);

            Console.WriteLine("執行同步的時間:" + synchroDateStr);

            return sleepDT;
        }

        #endregion 計算剩餘時間

        #region 主程式啟動

        //開始運作  
        public static void Main(string[] args)
        {
            mythread = new Thread(new ThreadStart(work));
            mythread.Start();
        }


        public static void work()
        {
            while (true)
            {
                //string synchroDateStr = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd 00:00:00");
                string synchroDateStr = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd 00:00:00");
                int sleepMilliseconds = CompareDate(synchroDateStr);
                Thread.Sleep(sleepMilliseconds);
                dowork();//方法放到後邊,可以避免在系統啟動的時候立即執行
            }
        }

        public static void dowork()
        {
            Console.WriteLine("123");
        }

        #endregion
    }
}
           

隻是實作了功能,想要使用的話還需修改

黑色頭發:http://heisetoufa.iteye.com/

繼續閱讀