.NET如何设置定时器

1、先创建一个.NET Framework 4.0的类库,名称为AlertToResponsible

2、创建一个类,比如AlertToResponsible类

Singleton

public class AlertToResponsible

{

//创建定时器

Create

public static void CreateInstance()

{

System.Diagnostics.Debug.Assert(self == null

, "self == null"

, "AlertToResponsible Subsystem is already started");

self = new AlertToResponsible();

}

Update

public static void UpdateInstance()

{

}

//设置定时器比如一小时启动一次

private AlertToResponsible()

{

System.Timers.Timer timer = new System.Timers.Timer();

timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

timer.Interval = 1000 * 60 * 60;

timer.Enabled = true;

}

//触发定时器

void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

{

try

{

DateTime time = DateTime.Now;

int h = time.Hour;

Log("触发器触发!");

//设定每天早晨九点开始发送消息

if (h == 9)

{

Log("触发器起效,开始发送消息!");

SendResponse();

}

}

catch (System.Exception ex)

{

}

}

//你发送消息的逻辑代码

private void SendResponse()

{

DateTime time = DateTime.Now;

Log("现在是北京时间:"+time);

}

//记录到日志

private void Log(string LogStr)

{

StreamWriter sw = null;

try

{

sw = new StreamWriter("C:\\PLMLoggerData\\PLMTimer" + DateTime.Now.ToShortDateString().Replace("/", "") + ".txt", true);

sw.WriteLine(DateTime.Now.ToString() + ":" + LogStr);

}

catch

{

}

finally

{

if (sw != null)

{

sw.Close();

}

}

}

private static AlertToResponsible self = null;

}

相关推荐
王多鱼鱼鱼11 分钟前
QT如何将exe打包成可执行文件
开发语言·qt
DokiDoki之父14 分钟前
边写软件边学kotlin(一):Kotlin语法初认识:
android·开发语言·kotlin
liu****15 分钟前
Qt进阶实战:事件处理、文件操作、多线程与网络编程全解析
开发语言·网络·数据结构·c++·qt
草原上唱山歌17 分钟前
C++如何调用Python代码
开发语言·c++·python
木子啊19 分钟前
PHP中间件:ThinkCMF 6.x核心利器解析
开发语言·中间件·php
崇山峻岭之间20 分钟前
Matlab学习记录40
开发语言·学习·matlab
Java后端的Ai之路21 分钟前
【Python教程11】-文件
开发语言·python
先做个垃圾出来………30 分钟前
SortedList(2)
开发语言
云栖梦泽31 分钟前
易语言开发从入门到精通:补充篇·文件批量操作深度实战·常用格式处理·自动化脚本开发·性能优化
开发语言
gc_229935 分钟前
学习C#调用OpenXml操作word文档的基本用法(21:学习嵌入对象类)
c#·word·openxml·ole