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

}

相关推荐
无限进步_4 分钟前
扫雷游戏的设计与实现:扫雷游戏3.0
c语言·开发语言·c++·后端·算法·游戏·游戏程序
qq_433554549 分钟前
C++ 完全背包
开发语言·c++·算法
追逐时光者16 分钟前
使用 Visual Studio 快速创建 NuGet 程序包并发布到 NuGet 官网
后端·.net·visual studio
青铜弟弟24 分钟前
R语言利用Export包导出pptx格式的文件有错误的原因
开发语言·r语言
Yupureki36 分钟前
从零开始的C++学习生活 8:list的入门使用
c语言·c++·学习·visual studio
Siren_dream36 分钟前
python进阶_Day8
开发语言·python
蓝天智能42 分钟前
QT QML交互原理:信号与槽机制
开发语言·qt·交互
十五年专注C++开发1 小时前
C++类型转换通用接口设计实现
开发语言·c++·跨平台·类设计
im_AMBER1 小时前
杂记 15
java·开发语言·算法
Zzz 小生1 小时前
编程基础学习(一)-Python基础语法+数据结构+面向对象全解析
开发语言·python