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

}

相关推荐
xwlcfyb2 分钟前
零基础学好C语言系列第八讲:初识指针
c语言·开发语言
非 白4 分钟前
【Java分布式】Nacos注册中心
java·开发语言·nacos·注册中心
88号技师5 分钟前
2025年2月最新SCI-鹰鱼优化算法HawkFish Optimization Algorithm-附Matlab免费代码
开发语言·算法·matlab·优化算法
Joey_friends1 小时前
【Linux】线程详解
开发语言
_GR1 小时前
Qt开发⑧Qt的窗口_下_浮动窗口+对话框
开发语言·css·c++·qt·microsoft
Good Note1 小时前
Golang——常用库context和runtime
开发语言·爬虫·golang
清河__2 小时前
【Go】十七、grpc 服务的具体功能编写
开发语言·后端·golang
张声录12 小时前
国密算法Sm2工具类--golang实现版
开发语言·后端·golang
吃汤圆的抹香鲸2 小时前
Rider 安装包 绿色版 Win/Mac/Linux 适合.NET和游戏开发者使用 2025全栈开发终极指南:从零配置到企业级实战
linux·运维·windows·sql·游戏·macos·.net
HH牛码2 小时前
C# 中 Array、ArrayList 和 List 的比较
开发语言·c#