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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值