2014-06-15 30 views
0

我已经在特定时间看到过设置计时器的类似帖子...我不想运行计时器整天...我想在特定时间启动它.. 大部分的建议是使用计划任务......但我想和窗口服务做到这一点....窗口服务:如何在特定时间启动计时器

这是我服务的工作代码:

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(); 
} 

但我不知道如何实现它的代码..

任何建议将是有益的

+0

只需检查已过期的处理程序中的“DateTime.Now”,看它是否在下午3点之后。如果是,写日志,如果没有,则什么也不做。 –

+0

其实我不想在每个5分钟的间隔运行计时器..我想在特定的时间启动它 –

+0

你不能,你要么检查它每隔一段时间或你安排它。没有办法让它知道时间现在是3PM –

回答

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


    } 
+0

你刚刚圆了秒,它不会开始于3PM作为OP想... –

+0

谢谢KB .. 。我正在实现并试图理解它 –

+0

是的我认为OP是想达到什么,因为否则计时器滴答是硬件中断 –

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!! 
}