【问题标题】:how to set up a timer in a C# windows windows service如何在 C# windows windows 服务中设置计时器
【发布时间】:2014-02-20 08:21:30
【问题描述】:
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");
    }

在我的 Windows 服务中的上述示例代码中,无论服务是否停止、重新启动或服务器是否重新启动,我如何获取到当前或下个月的下一个 7 天的秒数?。

【问题讨论】:

    标签: c# c#-4.0 timer windows-services


    【解决方案1】:

    您可以使用此实用程序函数来获取对应于本月或下个月的下一个 nth 的 DateTime

    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;
    

    【讨论】:

    • 如果 secondsTo7thDay 是 63529747200.0 我得到以下异常“数字必须是非负数且小于或等于 Int32.MaxValue 或 -1。参数名称:dueTime”设置计时器间隔时。参数dueTime接受的最大值是多少?
    • 我不知道这个限制。整数的最大值为2,147,483,647。或许更好的解决方案是将时间间隔设置为 1 小时,然后在 Elapsed 事件中检查当前日期和时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多