有时候我们需要每天 定时的 自动 去执行某段程序,那么这个功能如何实现呢? 经过百度,定时器就可以实现,总结如下:

我用控制台写了一个程序,用来在指定时间内 打印 “我执行了”

定时执行某段程序

上面就是程序的运行结构,由于我设置了循环,所以输出了多次

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
   
    class Program
    {
        public static int n = 0;
        public static string time = "14:41:0";//设置在每天下午2点26分执行
        static void Main(string[] args)
        {
           //指定时间执行一段程序
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Enabled = true;
            timer.Interval = 1000;//执行间隔时间,单位为毫秒   这里我设置的每隔1秒执行一次程序
            timer.Start();          
            timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer1_Elapsed);
            Console.ReadKey();
        }
        
        private static void Timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            DateTime dt = DateTime.Now;
            string currentTime = string.Format("{0}:{1}:{2}", dt.Hour.ToString(), dt.Minute.ToString(), dt.Second.ToString());
            Console.WriteLine(currentTime);
            if (currentTime==time)//如果到了我们指定的时间,则提示“我执行了”
            {
                for (int i = 0; i < 1000; i++)
                {
                    Console.WriteLine("我执行了!");                   
                }               
               
            }         
          
        }
    }
}
View Code

相关文章: