美文网首页
定时器简单用法

定时器简单用法

作者: 向着远方奔跑 | 来源:发表于2018-09-10 22:55 被阅读0次

问题1:

如何使一个label显示出提示文字后,经过一定的时间自动消失?

  • 代码如下:
//实例化窗体定时器
System.Windows.Form.Timer ti = new System.Windows.Form.Timer();

        private void Timer()
        {
            //给timer挂起事件  
            ti.Tick += new EventHandler(Callback);
            //使timer可用  
            ti.Enabled = true;
            //设置时间间隔,以毫秒为单位  
            ti.Interval = 3000;//3s 
        }

//回调函数  
        private void Callback(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(label1.Text))
            {
                label1.Text = "";
            }
            ti.Stop();
        }
  • 使用方法:
    在每次 label给出提示后,调用 Timer() 即可
label1.Text = "任务发送成功";
Timer();

问题2:

不用控件 , 只实现定时功能

  • 代码如下:
using System;
using System.Timers;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            RemenberTime();//调用控制器
            Console.Read();
        }
        public static void RemenberTime()
        {
            System.Timers.Timer timer = new System.Timers.Timer(1000);//设定计时器,1秒进行一次循环
            timer.Elapsed += new System.Timers.ElapsedEventHandler(Start);
            //timer.Interval = 1000;//设置时间(定时器多少秒执行一次--注意是毫秒)
            //System.Timers.Timer timer = new System.Timers.Timer(1000);与上作用一样
            timer.AutoReset = true;//执行多次--false执行一次
            timer.Enabled = true;//执行事件为true,定时器启动
            //timer.Start();//定时器启动Start()这个方法与timer.Enabled = true;作用一样,二者写一个就可以
            //timer.Stop();//定时器停止Stop()这个方法与timer.Enabled = false;作用一样,二者写一个就可以
        }
        public static void Start(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine(DateTime.Now.ToString());
        }
    }
}

效果如下

相关文章

网友评论

      本文标题:定时器简单用法

      本文链接:https://www.haomeiwen.com/subject/tfoegftx.html