.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;

}

相关推荐
2501_926227941 小时前
.Net程序员就业现状以及学习路线图(五)
学习·.net
希望20172 小时前
Golang Panic & Throw & Map/Channel 并发笔记
开发语言·golang
朗迹 - 张伟2 小时前
Golang安装笔记
开发语言·笔记·golang
yzx9910132 小时前
生活在数字世界:一份人人都能看懂的网络安全生存指南
运维·开发语言·网络·人工智能·自动化
小周同学@2 小时前
谈谈对this的理解
开发语言·前端·javascript
橙*^O^*安3 小时前
Go 语言基础:变量与常量
运维·开发语言·后端·golang·kubernetes
NiKo_W3 小时前
Linux 文件系统与基础指令
linux·开发语言·指令
工程师小星星3 小时前
Golang语言的文件组织方式
开发语言·后端·golang
乂爻yiyao3 小时前
java 代理模式实现
java·开发语言·代理模式
张子夜 iiii4 小时前
实战项目-----Python+OpenCV 实现对视频的椒盐噪声注入与实时平滑还原”
开发语言·python·opencv·计算机视觉