// 定义计时器对象
1 public class CountDown 2 { 3 4 private static CountDown theCountDown = null; 5 private static readonly object _padLock = new object(); // unique object for lock 6 7 private Timer timer = null; //计时器 8 private int dt; 9 10 /// <summary> 11 /// decide logic 12 /// </summary> 13 public int DT 14 { 15 get; 16 set; 17 } 18 19 private CountDown () 20 { 21 timer = new Timer(); 22 timer.Interval = 60000; // 1 min to elapsed 23 dt = 0; 24 DT = 0; 25 timer.Elapsed += timer_Elapsed; 26 } 27 28 private void timer_Elapsed(object sender, ElapsedEventArgs e) 29 { 30 dt--; 31 if (dt<=0) 32 { 33 timer.Stop(); 34 } 35 DT = dt; // update DT for logic 36 } 37 38 39 /// <summary> 40 /// start timer by using param to set times of loop 41 /// </summary> 42 /// <param name="times"></param> 43 public void Start(int times) 44 { 45 if (dt <=0) 46 { 47 dt = times; 48 timer.Start(); 49 } 50 51 } 52 53 /// <summary> 54 /// start timer 60 times loop as default 55 /// </summary> 56 public void Start() 57 { 58 if (dt <= 0) 59 { 60 dt = 60; 61 timer.Start(); 62 } 63 64 } 65 66 /// <summary> 67 /// stop timer 68 /// </summary> 69 public void Stop() 70 { 71 timer.Stop(); 72 } 73 74 /// <summary> 75 /// 实例化定时器 76 /// </summary> 77 /// <returns></returns> 78 public static CountDown Instance() 79 { 80 //判定对象是否实例化 81 if (null == theCountDown) 82 { 83 lock (_padLock)// 添加线程锁 84 { 85 if (null == theCountDown) 86 { 87 theCountDown = new CountDown(); 88 } 89 } 90 91 } 92 return theCountDown; 93 } 94 }
1 //实例化对象 2 CountDown cd = CountDown.Instance(); 3 if (cd.DT <= 0) 4 { 7 8 // TODO Something: 9 10 cd.Start(60); //开始计时,设定循环次数(1小时后,才可以再次调用该逻辑) 11 }