Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#windows服务中设置计时器_C#_C# 4.0_Timer_Windows Services - Fatal编程技术网

如何在C#windows服务中设置计时器

如何在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

在我的Windows服务的上面的示例代码中,我如何获得当前或下个月的下一个第7天的秒数,而不管服务是否已停止,重新启动或服务器已重新启动?

您可以使用此实用程序功能获取与本月或下一个月的下一个
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;