如何在C#windows服务中设置计时器
在我的Windows服务的上面的示例代码中,我如何获得当前或下个月的下一个第7天的秒数,而不管服务是否已停止,重新启动或服务器已重新启动?您可以使用此实用程序功能获取与本月或下一个月的下一个如何在C#windows服务中设置计时器,c#,c#-4.0,timer,windows-services,C#,C# 4.0,Timer,Windows Services,在我的Windows服务的上面的示例代码中,我如何获得当前或下个月的下一个第7天的秒数,而不管服务是否已停止,重新启动或服务器已重新启动?您可以使用此实用程序功能获取与本月或下一个月的下一个n日相对应的DateTime System.Timers.Timer scheduleTimer = new System.Timers.Timer(); DateTime dtPrevDate = new DateTime(); public Service1() { In
n
日相对应的DateTime
System.Timers.Timer scheduleTimer = new System.Timers.Timer();
DateTime dtPrevDate = new DateTime();
public Service1()
{
InitializeComponent();
scheduleTimer.Enabled = true;
int timerInterval = //number of seconds to the next 7th day of either current or next month;
scheduleTimer.Interval = timerInterval
scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);
}
protected override void OnStart(string[] args)
{
this.scheduleTimer.Start();
dtPrevDate = DateTime.Now.Date;
Logger.CreateLog("Service started");
}
如果secondsTo7thDay为63529747200.0,则在设置计时器间隔时,会出现以下异常“数字必须为非负且小于或等于Int32.MaxValue或-1.参数名称:dueTime”。参数dueTime接受的最大值是多少?我不知道这个限制。整数的最大值为
2147483647
。也许更好的解决方案是将间隔设置为1小时,然后在appeased
事件中检查当前日期和时间。
private DateTime GetNthDay(int n)
{
DateTime today = DateTime.Today;
DateTime nthDay = new DateTime(today.Year, today.Month, n);
if ( nthDay <= today )
{
nthDay = nthDay.AddMonths(1);
}
return nthDay;
}
DateTime dtPrevDate = DateTime.Now;
DateTime dtNextDate = GetNthDay(7);
Double secondsTo7thDay = (dtNextDate - dtPrevDate).TotalSeconds;