日期:2014-05-17  浏览次数:20973 次

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/