首页 > Windows开发 > 详细

[C#]System.Timers.Timer

时间:2016-09-07 14:39:33      阅读:283      评论:0      收藏:0      [点我收藏+]

摘要

在.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的时候,你要考虑到业务需求,是执行一次,还是不停的执行。

[C#]System.Timers.Timer

原文:http://www.cnblogs.com/wolf-sun/p/5849229.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!