场景
C#中实现计时器功能(定时任务和计时多长时间后执行某方法):
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106274074
前面讲的计时器的实现,如果需要一个Winform程序在每天的指定之间段内执行一次。
比如每天的交接班时间:7点50到8点之间、15点50到16点之间、23点50到24点之间分别执行一次定时任务。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
实现
1、时间段的间隔是10分钟,只要指定一个定时器检测当前时间是否位于以上时间区间内即可。
定时器执行的间隔需要小于10分钟,比如这里设置8分钟执行一次。
新增定时器并设置执行间隔
//定时器 Timer _timer = new Timer(); //定时器执行时间间隔 private int scheduleInterval = 1000 * 60 * 8;
2、设置定时器执行事件并启动定时器
_timer.Interval = scheduleInterval; _timer.Tick += _timer_Tick; _timer.Start();
3、在定时器执行事件中
private void _timer_Tick(object sender, EventArgs e) { //如果当前是应该执行定时任务的时间段 if (checkShoudStratTask()) { textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":获取候车硐室车辆定时任务执行"); textBox_log.AppendText("\r\n"); getCarListData(); } }
调用检查当前事件是否位于指定时间间隔之内的方法
private bool checkShoudStratTask() { //获取当前时间 DateTime now = DateTime.Now; DateTime sevenClock50 = DateTime.Today.AddHours(7).AddMinutes(50); DateTime eightClock = DateTime.Today.AddHours(8); DateTime fifteen50 = DateTime.Today.AddHours(15).AddMinutes(50); DateTime sixteenClock = DateTime.Today.AddHours(16); DateTime twentyThree50 = DateTime.Today.AddHours(23).AddMinutes(50); DateTime twentyFour = DateTime.Today.AddHours(24); //如果大于7点50 且小于8点 if ((sevenClock50 < now && now < eightClock) || (fifteen50 < now && now < sixteenClock) || (twentyThree50 < now && now < twentyFour) ) { return true; }else { return false; } }