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

本文关键字:定时间 启动 定时器 服务 窗口 | 更新日期: 2023-09-27 18:08:52

我看到过类似的在特定时间设置定时器的帖子…我不想一整天都计时……我想在特定的时间开始。大多数建议是使用计划任务…但是我想用窗口服务....

这是我的服务工作代码:

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秒的间隔添加日志。但我想启动定时器,让我们说下午三点…

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

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

任何建议都会有帮助

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

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

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

这里有一个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;  
        }

    }