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

}

相关推荐
悟能不能悟1 小时前
讲一件Java虚拟线程
java·开发语言·oracle
sjg200104141 小时前
golang学习随便记x[2,3]-字符串处理与正则表达式
开发语言·学习·golang
fictionist1 小时前
动态 Web 开发技术入门篇
java·服务器·开发语言·笔记·学习·mysql·spring
C MIKE1 小时前
ztree.js前端插件样式文字大小文字背景修改
开发语言·前端·javascript
PN杰1 小时前
Matlab解决无法读取路径中的空格
开发语言·matlab·dsp开发
Rose 使者1 小时前
全国天气预报查询接口如何用C#进行调用?
c#·api·天气预报
Simple_core2 小时前
qt3d自定义生成mesh图形
开发语言·qt·3d
夕泠爱吃糖2 小时前
Linux 文件内容的查询与统计
android·linux·c#
小码编匠2 小时前
WinForm 工业自动化上位机通用框架:注册登录及主界面切换实现
后端·c#·.net
码小跳2 小时前
Halcon案例(三):C#联合Halcon识别排线
计算机视觉·c#·halcon