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

}

相关推荐
枫叶丹44 分钟前
语音 AI 怎样边听边答:实时对话系统的工作原理
开发语言·人工智能·chatgpt·开源·php·agent·codex
xie0510_13 分钟前
Any类简要实现
开发语言·c++·算法
小狼Solar16 分钟前
SAP MDG 功能范围说明(基于S/4HANA 2025)
java·开发语言
kimnoic16 分钟前
Python常用标准库模块及查询使用方法
开发语言·python
知识分享小能手32 分钟前
C学习教程,从入门到精通,C语言输入和输出(4)
c语言·开发语言·学习
道尔柯南32 分钟前
C++ 入门基础详解:从第一个程序到核心语法特性
开发语言·c++
盛世宏博智慧档案34 分钟前
Modbus TCP+PoE以太网温湿度传感器项目部署全流程,附网络调试实操
开发语言·tcp/ip·php·以太网·传感器·温湿度
ACP广源盛1392462567336 分钟前
Type-C 扩展坞方案选型笔记|国产 DP1.2 转 HDMI2.0 桥接芯片 GSV2201D@ACP 评估
开发语言·笔记·硬件架构·硬件工程·hdmi·国产芯片
yuniko-n1 小时前
【JUC】线程间通信
java·开发语言
yuniko-n1 小时前
【JUC】关于 Java 线程介绍
java·开发语言