C#:用定时器监控定时器,实现中止定时器正在执行的任务,并重启

本文主要是介绍C#:用定时器监控定时器,实现中止定时器正在执行的任务,并重启,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Windows服务中使用的比较多的是定时器,但这种定时任务有个比较大的毛病:有时会莫名其妙地停止执行(长时间执行不完,假死),必须得手工重启Windows服务才能恢复正常。这个就太麻烦了。

有没有办法来实现定时器出现问题时自动重启定时器呢?我们做个小实验:

一、能否用Stop来中止定时器正在执行的任务?不行。

using System;
using System.Timers;namespace TestTimer
{internal class Program{private static int usingResource = 0;static int m = 0;static Timer timerTask = new Timer();static Timer timerMonitor = new Timer();static void Main(string[] args){//任务 定时器timerTask.AutoReset = true;timerTask.Interval = 1 * 1000;//1秒触发一次timerTask.Enabled = true;timerTask.Elapsed += TimerTask_Elapsed;timerTask.Start();//监控 定时器timerMonitor.AutoReset = true;timerMonitor.Interval = 1 * 1000;//1秒触发一次timerMonitor.Enabled = true;timerMonitor.Elapsed += TimerMonitor_Elapsed; ;timerMonitor.Start();Console.Read();}private static void TimerMonitor_Elapsed(object sender, ElapsedEventArgs e){Console.WriteLine("m={0}", m);if (m == 1){Console.WriteLine("set task stop");timerTask.Stop();}}private static void TimerTask_Elapsed(object sender, ElapsedEventArgs e){if (0 == System.Threading.Interlocked.Exchange(ref usingResource, 1)){m = new Random().Next(0, 2);//m只可能为0或1if (m == 0)Console.WriteLine("m=0 => {0:HH:mm:ss}", DateTime.Now);else{for (int i = 0; i < 999999999; i++){Console.WriteLine("m=1 => {0:HH:mm:ss}", DateTime.Now);System.Threading.Thread.Sleep(1000);}}System.Threading.Interlocked.Exchange(ref usingResource, 0);}else{Console.WriteLine("{0:yyyy-MM-dd HH:mm:ss}, 未取得锁,已退出", DateTime.Now);}}}
}

由上面代码可以得到下面的结果:

没有停止。

===================== 华丽的分隔线 =====================

二、直接中止线程来中止执行,并重启定时器:可以

下面的代码成功实现了用定时器TimerMonitor监控定时器TimerTask,如果有问题则立即中止TimerTask的线程,并实现重启TimerTask定时器的功能。

using System;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;namespace TestTimer
{internal class Program{private static int usingResourceTask = 0;private static int usingResourceMonitor = 0;static int m = 0;static Timer timerTask = new Timer();static Timer timerMonitor = new Timer();static Thread taskThread = null;static void Main(string[] args){//任务 定时器timerTask.AutoReset = true;timerTask.Interval = 2 * 1000;//2秒触发一次timerTask.Enabled = true;timerTask.Elapsed += TimerTask_Elapsed;timerTask.Start();//监控 定时器timerMonitor.AutoReset = true;timerMonitor.Interval = 2 * 1000;//2秒触发一次timerMonitor.Enabled = true;timerMonitor.Elapsed += TimerMonitor_Elapsed; ;timerMonitor.Start();Console.Read();}private static void TimerMonitor_Elapsed(object sender, ElapsedEventArgs e){if (0 == System.Threading.Interlocked.Exchange(ref usingResourceMonitor, 1)){Console.WriteLine("TimerMonitor {0}=> m={1}", DateTime.Now.ToString("HH:mm:ss"), m);if (m == 1)//用这个模拟出现了异常现象{m = 0;  //避免后一次快速进入Console.WriteLine("TimerMonitor {0}=> 即将中止 timerTask 线程 ", DateTime.Now.ToString("HH:mm:ss"));taskThread.Abort();Console.WriteLine("TimerMonitor {0}=> 已将 timerTask 执行停止", DateTime.Now.ToString("HH:mm:ss"));Thread.Sleep(10 * 1000);//暂停10秒,再重启定时器timerTask.Stop();Console.WriteLine("TimerMonitor {0}=> Task定时器在中止后10秒已设置为停止状态", DateTime.Now.ToString("HH:mm:ss"));//将任务的锁释放System.Threading.Interlocked.Exchange(ref usingResourceTask, 0);timerTask.Start();Console.WriteLine("TimerMonitor {0}=> Task定时器已设置为开启", DateTime.Now.ToString("HH:mm:ss"));}System.Threading.Interlocked.Exchange(ref usingResourceMonitor, 0);}else{//Console.WriteLine("TimerMonitor {0:yyyy-MM-dd HH:mm:ss}, 未取得锁,已退出", DateTime.Now);}}private static void TimerTask_Elapsed(object sender, ElapsedEventArgs e){taskThread = Thread.CurrentThread;if (0 == System.Threading.Interlocked.Exchange(ref usingResourceTask, 1)){m = new Random().Next(0, 2);//m只可能为0或1if (m == 0)Console.WriteLine("TimerTask m=0 => {0:HH:mm:ss}", DateTime.Now);else{for (int i = 0; i < 999999999; i++){Console.WriteLine("TimerTask m=1 => {0:HH:mm:ss}", DateTime.Now);System.Threading.Thread.Sleep(1000);}}System.Threading.Interlocked.Exchange(ref usingResourceTask, 0);}else{//Console.WriteLine("TimerTask {0:yyyy-MM-dd HH:mm:ss}, 未取得锁,已退出", DateTime.Now);}}}
}

这篇关于C#:用定时器监控定时器,实现中止定时器正在执行的任务,并重启的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/887759

相关文章

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

一文解析C#中的StringSplitOptions枚举

《一文解析C#中的StringSplitOptions枚举》StringSplitOptions是C#中的一个枚举类型,用于控制string.Split()方法分割字符串时的行为,核心作用是处理分割后... 目录C#的StringSplitOptions枚举1.StringSplitOptions枚举的常用

Python实现字典转字符串的五种方法

《Python实现字典转字符串的五种方法》本文介绍了在Python中如何将字典数据结构转换为字符串格式的多种方法,首先可以通过内置的str()函数进行简单转换;其次利用ison.dumps()函数能够... 目录1、使用json模块的dumps方法:2、使用str方法:3、使用循环和字符串拼接:4、使用字符

Linux下利用select实现串口数据读取过程

《Linux下利用select实现串口数据读取过程》文章介绍Linux中使用select、poll或epoll实现串口数据读取,通过I/O多路复用机制在数据到达时触发读取,避免持续轮询,示例代码展示设... 目录示例代码(使用select实现)代码解释总结在 linux 系统里,我们可以借助 select、

Linux挂载linux/Windows共享目录实现方式

《Linux挂载linux/Windows共享目录实现方式》:本文主要介绍Linux挂载linux/Windows共享目录实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录文件共享协议linux环境作为服务端(NFS)在服务器端安装 NFS创建要共享的目录修改 NFS 配