在编程中会经常用到定时器,使用最多是System.Window.Form下面的Timer控件或者System.Threading下面的Timer,前者需要在winform中使用,而后者提供的功能很简单,不能没有提供start和stop形式,即只能调用一次。所以就自己基于Thread实现了一个简单的定时器,只是用于简单的耗时少的定时处理任务的情况。
(1)思路
创建一个线程,在线程执行函数中,使用一个可控的循环,在循环内执行一个耗时很少的任务,在任务执行完之后,让线程Sleep规定的时间。
(2)代码
using System; using System.Collections.Generic; using System.Threading; using System.Text; namespace Wfl.Utility.Common.Tools { /// <summary> /// 基于线程实现的定时器 /// </summary> public class ThreadTimer { /// <summary> /// 线程 /// </summary> private Thread _thread; /// <summary> /// 标识线程是否执行 /// </summary> private volatile bool _isRunning; /// <summary> /// 定时器的间隔时间 /// </summary> private int _intervalSeconds; /// <summary> /// 回调函数 /// </summary> private ThreadTimerCallback _callback; /// <summary> /// 回调函数 /// </summary> private ThreadTimerCallbackParam _callbackParam; /// <summary> /// 每次线程休息的时间毫秒数 /// </summary> private int _sleepMicseconds; /// <summary> /// 构造函数 /// </summary> /// <param name="callback"></param> public ThreadTimer(ThreadTimerCallback callback,int intervalSeconds) { _callback = callback; _intervalSeconds = intervalSeconds; _sleepMicseconds = 100; } /// <summary> /// 构造函数 /// </summary> /// <param name="callbackParam"></param> public ThreadTimer(ThreadTimerCallbackParam callbackParam, int intervalSeconds) { _callbackParam = callbackParam; _intervalSeconds = intervalSeconds; _sleepMicseconds = 100; } /// <summary> /// 启动定时器 /// </summary> public void StartTimer() { _isRunning = true; _thread = new Thread(new ThreadStart(IntervalCall)); _thread.Start(); } /// <summary> /// 启动定时器 /// </summary> /// <param name="objParams"></param> public void StartTimer(object[] objParams) { _isRunning = true; _thread = new Thread(new ParameterizedThreadStart(IntervalCall)); _thread.Start(objParams); } /// <summary> /// 停止定时器 /// </summary> public void StopTimer() { _isRunning = false; try { _thread.Join(); } catch { } } /// <summary> /// 线程函数,定时调用回调函数 /// </summary> private void IntervalCall() { int runTime = _intervalSeconds * 1000; int curTime = 0; while (_isRunning) { if (curTime == runTime) { curTime = 0; _callback(); //该函数应该很快返回,耗时很少 } else { Thread.Sleep(_sleepMicseconds); curTime += _sleepMicseconds; } } } /// <summary> /// 线程函数,定时调用回调函数 /// </summary> /// <param name="obj"></param> private void IntervalCall(object obj) { object[] objParams = obj as object[]; int runTime = _intervalSeconds * 1000; int curTime = 0; while (_isRunning) { if (curTime == runTime) { curTime = 0; _callbackParam(objParams); //该函数应该很快返回,耗时很少 } else { Thread.Sleep(_sleepMicseconds); curTime += _sleepMicseconds; } } } } }
(3)测试代码
class Program { static void Main(string[] args) { ThreadTimer timer = new ThreadTimer(new ThreadTimerCallback(DoWork), 1); timer.StartTimer(); for (int i = 0; i < 10; i++) { Console.WriteLine(i); Thread.Sleep(1000); } Console.ReadKey(); timer.StopTimer(); } static void DoWork() { DateTime time = DateTime.Now; Console.WriteLine(time.ToString()); } }
(4)截图