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

}

相关推荐
long31615 分钟前
java 工厂方法设计模式 FactoryMethod
java·开发语言·后端·设计模式
柯南二号4 小时前
MacOS 系统计算机专业好用工具安装
开发语言·lua
神洛华4 小时前
Lua语言程序设计2:函数、输入输出、控制结构
开发语言·lua
java1234_小锋5 小时前
一周学会Matplotlib3 Python 数据可视化-绘制热力图(Heatmap)
开发语言·python·信息可视化·matplotlib·matplotlib3
梁辰兴5 小时前
数据结构:串、数组与广义表
开发语言·数据结构·c··数组·广义表
三体世界6 小时前
Mysql基本使用语句(一)
linux·开发语言·数据库·c++·sql·mysql·主键
etcix6 小时前
wrap cpp variant as dll for c to use
java·c语言·开发语言
Websites7 小时前
Hyperf 百度翻译接口实现方案
开发语言·自然语言处理·php·自动翻译
papership8 小时前
【入门级-C++程序设计:11、指针与引用-引 用】
c语言·开发语言·c++·青少年编程
常乐か9 小时前
VS2022+QT5.15.2+OCCT7.9.1的开发环境搭建流程
开发语言·qt·opencascade