zoukankan      html  css  js  c++  java
  • C#使用Timer.Interval指定时间间隔与指定时间执行事件

    C#中,Timer是一个定时器,它可以按照指定的时间间隔或者指定的时间执行一个事件。

    指定时间间隔是指按特定的时间间隔,如每1分钟、每10分钟、每1个小时等执行指定事件;

    指定时间是指每小时的第30分、每天10:30:30(每天的10点30分30秒)等执行指定的事件;

    在上述两种情况下,都需要使用 Timer.Interval,方法如下:

    1、按特定的时间间隔:

    using System;
    using System.Timers;
    
    namespace TimerExample
    {
        class Program
        {
    
            static void Main(string[] args)
            {
                System.Timers.Timer timer = new System.Timers.Timer();
                timer.Enabled = true;
                timer.Interval = 600000; //执行间隔时间,单位为毫秒; 这里实际间隔为10分钟  
                timer.Start();
                timer.Elapsed += new System.Timers.ElapsedEventHandler(test); 
    
                Console.ReadKey();
            }
    
            private static void test(object source, ElapsedEventArgs e)
            {
    
                  Console.WriteLine("OK, test event is fired at: " + DateTime.Now.ToString());
               
            }
        }
    }
    

      

    上述代码,timer.Inverval的时间单位为毫秒,600000为10分钟,所以,上代码是每隔10分钟执行一次事件test。注意这里是Console应用程序,所以在主程序Main中,需要有Console.Readkey()保持Console窗口不关闭,否则,该程序执行后一闪就关闭,不会等10分钟的时间。

    2、在指定的时刻运行:

    using System;
    using System.Timers;
    
    namespace TimerExample1
    {
        class Program
        {
    
            static void Main(string[] args)
            {
                System.Timers.Timer timer = new System.Timers.Timer();
                timer.Enabled = true;
                timer.Interval = 60000;//执行间隔时间,单位为毫秒;此时时间间隔为1分钟  
                timer.Start();
                timer.Elapsed += new System.Timers.ElapsedEventHandler(test); 
    
                Console.ReadKey();
            }
    
            private static void test(object source, ElapsedEventArgs e)
            {
    
                if (DateTime.Now.Hour == 10 && DateTime.Now.Minute == 30)  //如果当前时间是10点30分
                    Console.WriteLine("OK, event fired at: " + DateTime.Now.ToString());
                
            }
        }
    

      上述代码,是在指定的每天10:30分执行事件。这里需要注意的是,由于是指定到特定分钟执行事件,因此,timer.Inverval的时间间隔最长不得超过1分钟,否则,长于1分钟的时间间隔有可能会错过10:30分这个时间节点,从而导致无法触发该事件。

  • 相关阅读:
    MessageDigest类提供MD5或SHA等加密算法
    23种设计模式之策略设计模式
    n & (n-1)
    ubuntu 常用软件配置
    minicom 没有tx 信号
    usb 驱动
    全局变量的危害
    编写安全代码:小心volatile的原子性误解
    ADB Server Didn’t ACK ,failed to Start Daemon 解决方法
    字长
  • 原文地址:https://www.cnblogs.com/yachao1120/p/10494499.html
Copyright © 2011-2022 走看看