窗口服务:如何在特定时间启动计时器

时间:2014-06-15 07:35:16

标签: c# .net timer

我在特定时间看到类似的设置Timer的帖子...我不想运行计时器整天...我想在特定的时间启动它..  大多数建议是使用预定任务......但我想用窗口服务来做....

这是我的服务工作代码:

public AutoSMSService2()
{
    InitializeComponent();

    if (!System.Diagnostics.EventLog.SourceExists("MySource"))
    {
        System.Diagnostics.EventLog.CreateEventSource(
            "MySource", "MyNewLog");
    }
    eventLog1.Source = "MySource";
    eventLog1.Log = "MyNewLog";

    Timer checkForTime = new Timer(5000);
    checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
    checkForTime.Enabled = true;
}

protected override void OnStart(string[] args)
{
    eventLog1.WriteEntry("In OnStart");
}

protected override void OnStop()
{
    eventLog1.WriteEntry("In onStop."); 
}

void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
{
    eventLog1.WriteEntry("Timer Entry");
}

我的计时器工作正常并以5秒的间隔添加日志。但我想开始计时器让我们说下午3点......

private static void SetTimer(Timer timer, DateTime due) 
{
    var ts = due - DateTime.Now;
    timer.Interval = ts.TotalMilliseconds;
    timer.AutoReset = false;
    timer.Start();
}

但我不确定如何在代码中实现它..

任何建议都会有帮助

2 个答案:

答案 0 :(得分:0)

这里有一个windows窗体的例子,但你可以用windows服务实现一些东西

 public partial class Form1 : Form
{

    private bool _timerCorrectionDone = false;
    private int _normalInterval = 5000;  
    public Form1()
    {
        InitializeComponent();
        //here you calculate the second that should elapsed 
         var now  =  new TimeSpan(0,DateTime.Now.Minute, DateTime.Now.Second);
        int corrTo5MinutesUpper = (now.Minutes/5)*5;
        if (now.Minutes%5>0)
        {
             corrTo5MinutesUpper =  corrTo5MinutesUpper + 5; 
        }
        var upperBound = new TimeSpan(0,corrTo5MinutesUpper, 60-now.Seconds);
        var correcFirstStart = (upperBound - now);
        timer1.Interval = (int)correcFirstStart.TotalMilliseconds;
        timer1.Start();


    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        // just do a correction   like  this 
        if (!_timerCorrectionDone)
        {
            timer1.Interval = _normalInterval;
            _timerCorrectionDone = true;  
        }


    }

答案 1 :(得分:0)

如果你想每天都这样做,希望这会有所帮助。

private System.Threading.Timer myTimer;
private void SetTimerValue ()
{

   DateTime requiredTime = DateTime.Today.AddHours(15).AddMinutes(00);
   if (DateTime.Now > requiredTime)
   {
      requiredTime = requiredTime.AddDays(1);
   }


   myTimer = new System.Threading.Timer(new TimerCallback(TimerAction));
   myTimer.Change((int)(requiredTime - DateTime.Now).TotalMilliseconds, Timeout.Infinite);
}

private void TimerAction(object e)
{
   //here you can start your timer!!
}