简体   繁体   English

如何在每天的特定时间使用 c# 中的 topshelf 安排 windows 服务

[英]How to Schedule a windows service using topshelf in c# at specific time in a each day

_timer = new Timer(1.8e+6) { AutoReset = true };
_timer.Elapsed += TimerElapsed;

To make it run for a specific time of a day you have to make your timer set for that Time/value by finding out the difference from the current time when your service starts, find the difference between your current time and your specific time and sets the timer with that value.要使其在一天中的特定时间运行,您必须通过找出服务启动时与当前时间的差异来为该时间/值设置计时器,找到当前时间与特定时间之间的差异并设置具有该值的计时器。

public void Start() 
{
  ResetTimer();
}

public void TimerElapsed (object sender, ElapsedEventArgs e)
{
    // do whatever it is that you need to do on a timer
    ResetTimer();
}
public void ResetTimer()
{
        DateTime startTime=DateTime.Now;// = "current time";
        DateTime endTime = DateTime.Parse("Specific time to run the service");

        if (endTime < startTime)
        {
            endTime.AddDays(1);
        }           
        
        TimeSpan duration = endTime.Subtract(startTime);        
    
        _timer.Change(TimeSpan.FromSeconds(duration.Seconds), 
         TimeSpan.FromSeconds(duration.Seconds));
        _timer.Elapsed += TimerElapsed; //if not set

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM