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

时间:2014-02-20 08:21:31

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

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天的秒数?

1 个答案:

答案 0 :(得分:1)

您可以使用此实用程序功能获取与此月或下个月的下一个DateTime日对应的n

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;