一个简单的Timer计时器,设置到达时间隔时启动一次Timer(每次只执行一次),更加节省资源...
1.首先新建一个控制台应用程序;
2.在Program.cs里面添加如下代码:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Timer_TEST
{
class Program
{
private System.Timers.Timer _timer;
/// <summary>
/// 下次统计时间
/// </summary>
DateTime _nextTime = Convert.ToDateTime(DateTime.Now.AddMinutes(1).ToString("yyyy-MM-dd HH:mm:ss"));
/// <summary>
/// 获取下次执行
/// </summary>
/// <param name="args"></param>
double GetInterval()
{
double interval = Timeout.Infinite;
try
{
TimeSpan ts = _nextTime.Subtract(DateTime.Now);
interval = ts.Duration().TotalMilliseconds;
Console.WriteLine(string.Format("{0}秒后执行",(interval/1000).ToString()));
}
catch (Exception ex)
{
Console.WriteLine("获取下次执行报表服务的时间间隔失败,错误信息:", ex);
}
return interval;
}
/// <summary>
/// 启动定时器
/// </summary>
/// <param name="args"></param>
public void Start()
{
try
{
_timer = new System.Timers.Timer();
_timer.Enabled = true;
_timer.Interval = GetInterval();
_timer.AutoReset = false;//false为每次定时器只在间隔时间到达之后执行一次;true为定时器间隔时间到达后连续执行
_timer.Elapsed += new System.Timers.ElapsedEventHandler(ShowTime);//设定定时器执行时间
_timer.Start();
Program p = new Program();
p.ShowTime();
}
catch (Exception ex)
{
Console.WriteLine("定时器启动失败,失败信息:",ex);
}
}
private void ShowTime(object sender, System.Timers.ElapsedEventArgs e)
{
ShowTime();
//重新set定时器
_timer.Interval = GetInterval();
_timer.Start();
}
private void ShowTime()
{
//DateTime dt = Convert.ToDateTime(DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss"));
Console.WriteLine("现在时间是:" + DateTime.Now);
_nextTime = _nextTime.AddMinutes(1);
}
static void Main(string[] args)
{
Program p = new Program();
p.Start();
Console.ReadLine();
}
}
}