view ServerMonitor/Objects/Schedule.cs @ 4:3142e52cbe69

Lots more progress
author Brad Greco <brad@bgreco.net>
date Sun, 10 Feb 2019 20:51:26 -0500
parents 3e1a2131f897
children 052aa62cb42a
line wrap: on
line source

´╗┐using System;

namespace ServerMonitorApp
{
    public class Schedule
    {
        public Schedule() { }

        public Schedule(FrequencyUnits units, int frequency, TimeSpan startTime, TimeSpan endTime)
        {
            Units = units;
            Frequency = frequency;
            StartTime = startTime;
            EndTime = endTime;
        }

        public int Frequency { get; set; }

        public FrequencyUnits Units { get; set; }

        public TimeSpan StartTime { get; set; }

        public TimeSpan EndTime { get; set; }

        public DateTime GetNextTime(DateTime lastScheduledTime)
        {
            return GetNextTime(lastScheduledTime, DateTime.Now);
        }

        public DateTime GetNextTime(DateTime lastScheduledTime, DateTime minStartTime)
        {
            DateTime nextTime = lastScheduledTime;
            if (Units == FrequencyUnits.Day)
            {
                //TODO what if nextTime is null or really long ago?
                while (nextTime < minStartTime)
                    nextTime = nextTime.AddDays(Frequency).Date.Add(StartTime);
            }
            else
            {
                // If the last run time was more than a day ago, fast-forward to reduce the number of loops
                if (nextTime < minStartTime.AddHours(-24))
                    nextTime = minStartTime.Date.Add(StartTime).AddHours(-24);
                while (nextTime < minStartTime)
                {
                    switch (Units)
                    {
                        case FrequencyUnits.Second: nextTime = nextTime.AddSeconds(Frequency); break;
                        case FrequencyUnits.Minute: nextTime = nextTime.AddMinutes(Frequency); break;
                        case FrequencyUnits.Hour:   nextTime = nextTime.AddHours(Frequency);   break;
                        default: throw new InvalidOperationException("Unexpected frequency units: " + Units);
                    }
                }
                if (StartTime < EndTime)
                {
                    if (nextTime.TimeOfDay < StartTime)
                        nextTime = nextTime.Date + StartTime;
                    else if (nextTime.TimeOfDay > EndTime)
                        nextTime = nextTime.Date.AddDays(1) + StartTime;
                }
                else if (nextTime.TimeOfDay > EndTime && nextTime.TimeOfDay < StartTime)
                {
                    nextTime = nextTime.Date + StartTime;
                }
            }
            return nextTime;
        }
    }

    public enum FrequencyUnits { Second, Minute, Hour, Day }
}