0

我有一个 Windows 服务设置为在特定时间运行,它是第一次运行,但我似乎不知道如何告诉它在第二天结束时运行..

这就是我正在尝试的...

protected override void OnStart(string[] args)
    {
        log.Info("Info - Service Start");
        string timeToRunStr = "17:11";
        var timeStrArray = timeToRunStr.Split(';');
        foreach (var strTime in timeStrArray)
        {
            timeToRun.Add(TimeSpan.Parse(strTime));
        }
        ResetTimer();
    }

    void ResetTimer()
    {
        log.Info("Info - Reset Timer");
        try
        {
            TimeSpan currentTime = DateTime.Now.TimeOfDay;
            TimeSpan nextRunTime = timeToRun[0];
            foreach (TimeSpan runTime in timeToRun)
            {
                if (currentTime < runTime)
                {
                    nextRunTime = runTime;
                    // log.Info("Info - in loop");
                    break;
                }
                else {
                    TimeSpan test = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 16, 51, 0).Subtract(DateTime.Now);
                    nextRunTime = test;
                }
            }
            _timer = new Timer((nextRunTime - currentTime).TotalSeconds * 1000);
            log.Info("Info - Timer : " + (nextRunTime - currentTime).TotalSeconds * 1000);
            log.Info("Info - nextRuntime : " + nextRunTime);
            log.Info("Info - currentTime : " + currentTime);
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            _timer.Start();
        }
        catch (Exception ex)
        {
            log.Error("This is my timer error - ", ex);
        }
    }
4

1 回答 1

1

查看这些替代方案::
下一个凌晨 3 点发生的日期时间

使用计时器控制活动,参见模型:

class Program
{
    static void my_task(Object obj)
    {
        Console.WriteLine("task being performed.");
    }

    static TimerCallback timerDelegate;
    static Timer timer;

    static void Main(string[] args)
    {
        DateTime now = DateTime.Now;
        DateTime today = now.Date.AddHours(12);
        DateTime next = now <= today ? today : today.AddDays(1);

        timerDelegate = new TimerCallback(my_task);

        //                                     hence the first         after the next       
        timer = new Timer(timerDelegate, null, next - DateTime.Now, TimeSpan.FromHours(24));
    }
}
于 2012-06-19T18:49:36.497 回答