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

}

相关推荐
yaoxin52112312 小时前
462. Java 反射 - 获取声明类与封闭类
java·开发语言·python
阿里嘎多学长12 小时前
2026-07-14 GitHub 热点项目精选
开发语言·程序员·github·代码托管
charlie11451419113 小时前
Cinux: 为大内核铺路
开发语言·c++·操作系统·现代c++
2501_9142459313 小时前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
Hazenix14 小时前
Go 指南:一篇文章速通 Golang
开发语言·后端·golang
灯澜忆梦14 小时前
GO_复合类型---指针
开发语言·后端·golang
Ulyanov14 小时前
雷达导引头Python仿真框架:GPU加速、6-DOF模型与半实物仿真接口
开发语言·python·雷达信号处理·雷达导引头
名字还没想好☜15 小时前
Go slice 的 append 陷阱:共享底层数组导致的数据串改
开发语言·后端·golang·go·slice
bitbrowser15 小时前
Claude 账号频繁被封?转向国内可直接使用的 AI 工具
开发语言·php
An_s15 小时前
机器学习python之识别图中物品信息
java·linux·开发语言