[C#]System.Timers.Timer

摘要

在.Net中有几种定时器,最喜欢用的是System.Timers命名空间下的定时器,使用起来比较简单,作为定时任务,有Quartz.net,但有时候,一个非常简单的任务,不想引入这个定时任务框架,用Timer完全可以满足要求。

一个例子

每一秒在控制台上打印时间。

    class Program
    {
        static void Main(string[] args)
        {
            var timer = new System.Timers.Timer();
            timer.Elapsed += timer_Elapsed;

            timer.AutoReset = true;
            timer.Enabled = true;
            timer.Interval = 1000;
            Console.Read();
        }

        private static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Console.WriteLine(e.SignalTime.ToString());
        }
    }

 timer.AutoReset = true;注意,AutoReset属性,如果你希望到时间了,不停的执行Elapsed事件,要将其设置为true。它的作用类似js中的setInterval方法,如果为false,类似于js中的setTimerout方法,只执行一次。

所以在使用timer的时候,你要考虑到业务需求,是执行一次,还是不停的执行。

posted @ 2016-09-07 13:54  wolfy  阅读(11535)  评论(0编辑  收藏  举报