Example #1
0
        private (string name, TaskConfiguration taskConfiguration) CreateTaskConfiguration(CsissorsTaskAttribute taskAttribute, TimeSpan leaseDuration)
        {
            ISchedule schedule;

            if (taskAttribute.Schedule != null)
            {
                CronExpression cronExpression = CronExpression.Parse(taskAttribute.Schedule);
                TimeZoneInfo   timeZoneInfo   = taskAttribute.TimeZone != null
                    ? TimeZoneInfo.FindSystemTimeZoneById(taskAttribute.TimeZone)
                    : TimeZoneInfo.Utc;

                schedule = new CronSchedule(cronExpression, timeZoneInfo, taskAttribute.FastForward);
            }
            else
            {
                schedule = new IntervalSchedule(
                    new TimeSpan(taskAttribute.Days, taskAttribute.Hours, taskAttribute.Minutes, taskAttribute.Seconds),
                    taskAttribute.FastForward
                    );
            }
            var taskName = taskAttribute.Name ?? _methodInfo.Name;
            var data     = new Dictionary <string, object?>();

            return(taskName, new TaskConfiguration(
                       schedule,
                       taskAttribute.FailureMode,
                       taskAttribute.ExecutionMode,
                       leaseDuration,
                       data
                       ));
        }
Example #2
0
        private void RunSimpleJob()
        {
            var startTime = ConsoleEx.ReadLine("Start Time (UTC)", DateTime.UtcNow - TimeSpan.FromMinutes(1));
            var jobId     = ConsoleEx.ReadLine("JobId", "simpleJob001");

            var storageConnectionstring = Config.Root[Config.NAH_EHLISTENER_STORAGECONNECTIONSTRING];

            var syncProvider  = new BlobSynchronizationProvider(storageConnectionstring); // Responsible for Singleton Implementation
            var stateProvider = new BlobJobStateProvider(storageConnectionstring);        // Responsible for state
            var jobExecutor   = new JobExecutor(syncProvider, stateProvider);
            var every5Seconds = new IntervalSchedule(TimeSpan.FromSeconds(5));

            while (true)
            {
                jobExecutor.RunAsSingletonAsync(jobId, every5Seconds, (dt) =>
                {
                    Console.WriteLine($"Start Job for Time {dt}");
                    return(Task.CompletedTask);
                }, startTime).Wait();

                Console.Write(".");

                Thread.Sleep(1000);

                if (EscPressed())
                {
                    break;
                }
            }
        }
Example #3
0
        private void Test(object sender, System.EventArgs e)
        {
            MessageBox.Show("Test will now create all types of schedules and opens Schedules View");

            // create and add different types of schedules
            Schedule s = new IntervalSchedule("Test_Interval", DateTime.Now.AddMinutes(1), 45, TimeSpan.Zero, new TimeSpan(TimeSpan.TicksPerDay));

            s.OnTrigger += new EventScheduler.Invoke(ScheduleCallBack);
            Scheduler.AddSchedule(s);
            s            = new OneTimeSchedule("Test_Onetime", DateTime.Now.AddMinutes(1.5));
            s.OnTrigger += new EventScheduler.Invoke(ScheduleCallBack);
            Scheduler.AddSchedule(s);
            s            = new DailySchedule("Test_daily", DateTime.Now.AddMinutes(2));
            s.OnTrigger += new EventScheduler.Invoke(ScheduleCallBack);
            Scheduler.AddSchedule(s);
            s            = new WeeklySchedule("Test_weekly", DateTime.Now.AddMinutes(2.5));
            s.OnTrigger += new EventScheduler.Invoke(ScheduleCallBack);
            Scheduler.AddSchedule(s);
            s            = new MonthlySchedule("Test_monthly", DateTime.Now.AddMinutes(3));
            s.OnTrigger += new EventScheduler.Invoke(ScheduleCallBack);
            Scheduler.AddSchedule(s);

            // kick off the Schedules View
            SchedulerUI.ShowSchedules();
        }
 public void IntervalIntervalDefinedScheduleRoundTripDeserializesIntoBaseClass()
 {
     var schedule = new IntervalSchedule { Interval = TimeSpan.FromHours(2) };
     var json = JsonConvert.SerializeObject(schedule);
     var newScheduleBase = JsonConvert.DeserializeObject<ScheduleBase>(json);
     var newScheduleTyped = Assert.IsType<IntervalSchedule>(newScheduleBase);
     Assert.Equal(schedule.Interval, newScheduleTyped.Interval);
 }
 public void IntervalNoIntervalScheduleRoundTripDeserializesIntoBaseClass()
 {
     var schedule = new IntervalSchedule();
     var json = JsonConvert.SerializeObject(schedule);
     var newScheduleBase = JsonConvert.DeserializeObject<ScheduleBase>(json);
     var newScheduleTyped = Assert.IsType<IntervalSchedule>(newScheduleBase);
     Assert.Equal(schedule.Interval, newScheduleTyped.Interval);
 }
        public static void IntervalScheduleIntervalDefined_Valid()
        {
            var o = new IntervalSchedule {
                Interval = TimeSpan.FromHours(1)
            };

            Assert.NotNull(o);
            o.ThrowIfInvalid();
        }
        public void IntervalNoIntervalScheduleRoundtripWillDeserializeIntoBaseClass()
        {
            var schedule         = new IntervalSchedule();
            var json             = this.bsonSerializer.SerializeToString(schedule);
            var newScheduleBase  = this.bsonSerializer.Deserialize <ScheduleBase>(json);
            var newScheduleTyped = Assert.IsType <IntervalSchedule>(newScheduleBase);

            Assert.Equal(schedule.Interval, newScheduleTyped.Interval);
            Assert.Equal(schedule, newScheduleTyped);
        }
Example #8
0
        public void UpdateConfigurationFile(ConfigurationSettings configsettings)
        {
            CreateFoldersInRepositories();

            foreach (RepositoryArgumentsBase repository in configsettings.Repositories)
            {
                repositories[repository.Name] = repository;
            }

            OperationContextFactory.SetRepositories(repositories);

            using (IDatabaseRepository <IHarvesterDataContext> harvester = RepositoryFactory.CreateHarvesterRepository(repositories["Harvester"]))
            {
                foreach (KeyValuePair <String, RepositoryArgumentsBase> repo in repositories)
                {
                    if (harvester.DataContext.Repositories.All(x => x.Name != repo.Key))
                    {
                        harvester.DataContext.Repositories.InsertOnSubmit(new Entities.Repository
                        {
                            Name = repo.Key
                        });
                    }
                }

                harvester.DataContext.SubmitChanges();
            }

            foreach (OperationArgumentsBase operationArgs in configsettings.Operations)
            {
                RemoveOldOperations(operationArgs);

                ScheduleArgumentsBase[] schedules = operationArgs.Schedules;

                foreach (ScheduleArgumentsBase schedule in schedules)
                {
                    IntervalSchedule intervalSchedule = new IntervalSchedule((IntervalScheduleArguments)schedule);

                    IEnumerator <DateTime> enumerator = intervalSchedule.GetEnumerator();
                    enumerator.MoveNext();
                    try
                    {
                        AddOperation(OperationContextFactory.CreateOperationContext(operationArgs, enumerator));
                    }
                    catch (Exception ex)
                    {
                        if (ex.GetType() == typeof(KeyNotFoundException))
                        {
                            throw new KeyNotFoundException("Repository Missing: " + (KeyNotFoundException)ex.InnerException);
                        }
                        throw;
                    }
                }
            }
        }
        public void IntervalIntervalDefinedScheduleRoundtripWillDeserializeIntoBaseClass()
        {
            var schedule = new IntervalSchedule {
                Interval = TimeSpan.FromHours(2)
            };
            var json             = this.bsonSerializer.SerializeToString(schedule);
            var newScheduleBase  = this.bsonSerializer.Deserialize <ScheduleBase>(json);
            var newScheduleTyped = Assert.IsType <IntervalSchedule>(newScheduleBase);

            Assert.Equal(schedule.Interval, newScheduleTyped.Interval);
            Assert.Equal(schedule, newScheduleTyped);
        }
        public void RealTestCase()
        {
            var schedule = new IntervalSchedule(new DateTime(2019, 09, 25, 2, 1, 57, 662), TimeSpan.FromSeconds(1));
            //var lastCurrentTime = new DateTime(637049908146627031);
            //var lastNextTime = schedule.GetNextTime(lastCurrentTime);
            var curretTime = new DateTime(637049908156619372);
            var nextTime   = schedule.GetNextTime(curretTime);

            var expectedNextTime = new DateTime(2019, 09, 25, 6, 46, 55, 662);

            Assert.AreEqual(expectedNextTime, nextTime);
        }
        public static void GetCronExpressionFromSchedule_Interval_Works()
        {
            var schedule = new IntervalSchedule {
                Interval = TimeSpan.FromMinutes(1)
            };
            var cron = ScheduleCronExpressionConverter.ToCronExpression(schedule);

            Assert.Equal("* * * * *", cron);

            var newSchedule      = ScheduleCronExpressionConverter.FromCronExpression(cron);
            var newScheduleTyped = Assert.IsType <IntervalSchedule>(newSchedule);

            Assert.Equal(schedule.GetType(), newScheduleTyped.GetType());
            Assert.Equal(schedule.Interval, newScheduleTyped.Interval);
        }
Example #12
0
        public void IntervalScheduleTriggerTest()
        {
            Debug.WriteLine("------- Scheduling Jobs -------------------");

            var semHandle = new EventWaitHandle(false, EventResetMode.AutoReset);

            // Set the job run time.
            DateTime rangeStart  = DateTime.UtcNow;
            DateTime runTime     = rangeStart.AddSeconds(1);
            var      runSchedule = new IntervalSchedule(TimeSpan.FromMilliseconds(500), TimeSpan.Zero, rangeStart);

            // Define the job and tie it to our HelloJob class.
            JobDataMap jobDataMap = new JobDataMap((IDictionary <string, object>) new Dictionary <string, object> {
                { "SemHandle", semHandle }
            });

            IJobDetail job = JobBuilder.Create <HelloJob>()
                             .WithDescription("job1")
                             .WithIdentity("job1", "group1")
                             .UsingJobData(jobDataMap)
                             .Build();

            // Trigger the job to run on the set time.
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1")
                               .WithItinerarySchedule(runSchedule, rangeStart)
                               .Build();

            // Tell Quartz to schedule the job using our trigger.
            sched.ScheduleJob(job, trigger);
            var firstEvent = runSchedule.GetRange(rangeStart, DateTime.MaxValue).First();

            Debug.WriteLine(string.Format("{0} will start at: {1}", job.Description, firstEvent.StartTime.ToString("r")));

            // Start up the scheduler.
            sched.Start();
            Debug.WriteLine("------- Started Scheduler -----------------");

            // Wait long enough so that the scheduler as an opportunity to
            // run the job.
            Debug.WriteLine("------- Waiting a few seconds... -------------");

            // Wait for job to signal 5 times.
            for (int i = 0; i < 5; i++)
            {
                Assert.IsTrue(semHandle.WaitOne(5000));
            }
        }
        public void IntervalScheduleTriggerTest()
        {
            Debug.WriteLine("------- Scheduling Jobs -------------------");

             var semHandle = new EventWaitHandle(false, EventResetMode.AutoReset);

             // Set the job run time.
             DateTime rangeStart = DateTime.UtcNow;
             DateTime runTime = rangeStart.AddSeconds(1);
             var runSchedule = new IntervalSchedule(TimeSpan.FromMilliseconds(500), TimeSpan.Zero, rangeStart);

             // Define the job and tie it to our HelloJob class.
             JobDataMap jobDataMap = new JobDataMap((IDictionary<string, object>)new Dictionary<string, object> {
            { "SemHandle", semHandle }
             });

             IJobDetail job = JobBuilder.Create<HelloJob>()
            .WithDescription("job1")
            .WithIdentity("job1", "group1")
            .UsingJobData(jobDataMap)
            .Build();

             // Trigger the job to run on the set time.
             ITrigger trigger = TriggerBuilder.Create()
            .WithIdentity("trigger1", "group1")
            .WithItinerarySchedule(runSchedule, rangeStart)
            .Build();

             // Tell Quartz to schedule the job using our trigger.
             sched.ScheduleJob(job, trigger);
             var firstEvent = runSchedule.GetRange(rangeStart, DateTime.MaxValue).First();
             Debug.WriteLine(string.Format("{0} will start at: {1}", job.Description, firstEvent.StartTime.ToString("r")));

             // Start up the scheduler.
             sched.Start();
             Debug.WriteLine("------- Started Scheduler -----------------");

             // Wait long enough so that the scheduler as an opportunity to
             // run the job.
             Debug.WriteLine("------- Waiting a few seconds... -------------");

             // Wait for job to signal 5 times.
             for (int i = 0; i < 5; i++) {
            Assert.IsTrue(semHandle.WaitOne(5000));
             }
        }
Example #14
0
        public void TestSchedules()
        {
            var s1 = new DailySchedule(23, 55, 0);
            var dt = s1.GetNextExecutionTime(_dt1);

            Assert.Equal(_dt1.AddDays(1), dt);

            var s2 = new EveryHourOnTheHourSchedule();

            dt = s2.GetNextExecutionTime(_dt2);
            Assert.Equal(_dt2.AddHours(1), dt);

            var s3 = new EveryMinuteOnTheMinuteSchedule();

            dt = s3.GetNextExecutionTime(_dt3);
            Assert.Equal(_dt3.AddMinutes(1), dt);

            var s4 = new EveryQuarterOfAnHourSchedule();

            dt = s4.GetNextExecutionTime(_dt4);
            Assert.Equal(_dt4.AddMinutes(15), dt);

            var ts = new TimeSpan(3, 4, 0);
            var s5 = new IntervalSchedule(ts);

            dt = s5.GetNextExecutionTime(_dt4);
            Assert.Equal(_dt4 + ts, dt);

            ts = new TimeSpan(7, 5, 0);
            var s6 = new WeeklySchedule(ts, DayOfWeek.Monday, DayOfWeek.Wednesday);

            //_dt5 is Wednesday (2017, 6, 14, 7, 5, 00)
            dt = s6.GetNextExecutionTime(_dt5);
            //dt should be next Monday, which is 19/6
            Assert.Equal(_dt5.AddDays(5), dt);
            dt = s6.GetNextExecutionTime(_dt5.AddDays(5));
            //when it's executed on Monday 19/6, next execution should be on Wednesday 21/6
            Assert.Equal(_dt5.AddDays(7), dt);
            dt = s6.GetNextExecutionTime(_dt5.AddDays(7));
            //and after execution on Wednesday 21/6, next one should be 26/6
            Assert.Equal(_dt5.AddDays(12), dt);
        }
        public void IntervalScheduleTriggerTest()
        {
            Debug.WriteLine("------- Scheduling Jobs -------------------");

             var semHandle = new EventWaitHandle(false, EventResetMode.AutoReset);

             // Set the job run time.
             DateTime rangeStart = DateTime.UtcNow;
             DateTime runTime = rangeStart.AddSeconds(1);
             var runSchedule = new IntervalSchedule(TimeSpan.FromMilliseconds(500), TimeSpan.Zero, rangeStart);

             // Define the job and tie it to our HelloJob class.
             JobDetail job = new JobDetail("job1", "group1", typeof(HelloJob));
             job.JobDataMap["SemHandle"] = semHandle;

             // Trigger the job to run on the set time.
             var trigger = new ItineraryTrigger("trigger1", "group1", runSchedule, rangeStart);

             // Tell Quartz to schedule the job using our trigger.
             sched.ScheduleJob(job, trigger);
             var firstEvent = runSchedule.GetRange(rangeStart, DateTime.MaxValue).First();
             Debug.WriteLine(string.Format("{0} will start at: {1}", job.FullName, firstEvent.StartTime.ToString("r")));

             // Start up the scheduler.
             sched.Start();
             Debug.WriteLine("------- Started Scheduler -----------------");

             // Wait long enough so that the scheduler as an opportunity to
             // run the job.
             Debug.WriteLine("------- Waiting a few seconds... -------------");

             // Wait for job to signal 5 times.
             for (int i = 0; i < 5; i++) {
            Assert.IsTrue(semHandle.WaitOne(5000));
             }
        }
Example #16
0
        static void Main(string[] args)
        {
            // Create schedule programmatically.
            ISchedule schedule1        = new IntervalSchedule(TimeSpan.FromSeconds(11), TimeSpan.Zero, DateTime.MinValue);
            ISchedule schedule2        = new IntervalSchedule(TimeSpan.FromMinutes(1), TimeSpan.Zero, DateTime.MinValue.AddSeconds(1));
            ISchedule schedule3        = new CronSchedule("*/5", "*", "*", "*", "*", TimeSpan.Zero);
            ISchedule combinedSchedule = new ListSchedule(new[] { schedule1, schedule2, schedule3 });

            // Print schedule TDL.
            Console.WriteLine("Forecasting events from expression:\n{0}", combinedSchedule.ToString());

            // Forecast timed events for the next hour.
            IEnumerable <TimedEvent> events = combinedSchedule.GetRange(DateTime.Now, DateTime.Now.AddHours(1));

            int eventCount = events.Count();

            Console.WriteLine("Found {0:d} events.", eventCount);

            // Print to screen.
            foreach (TimedEvent e in events)
            {
                Console.WriteLine("Event time: {0:G}", e.StartTime);
            }
        }
        public void GetCronExpressionFromSchedule_Interval_Works()
        {
            var schedule = new IntervalSchedule { Interval = TimeSpan.FromMinutes(1) };
            var cron = ScheduleCronExpressionConverter.ToCronExpression(schedule);
            Assert.Equal("* * * * *", cron);

            var newSchedule = ScheduleCronExpressionConverter.FromCronExpression(cron);
            var newScheduleTyped = Assert.IsType<IntervalSchedule>(newSchedule);
            Assert.Equal(schedule.GetType(), newScheduleTyped.GetType());
            Assert.Equal(schedule.Interval, newScheduleTyped.Interval);
        }
Example #18
0
        public CronDummyFactory()
        {
            AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy <ScheduleBase>();

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var result = new DailyScheduleInUtc
                {
                    Hour   = A.Dummy <int>().ThatIsInRange(0, 23),
                    Minute = A.Dummy <int>().ThatIsInRange(0, 59),
                };

                return(result);
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var result = new ExpressionSchedule
                {
                    CronExpression = "*/" + A.Dummy <int>().ThatIsInRange(1, 4) + " * * * *",
                };

                return(result);
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var result = new HourlySchedule
                {
                    Minute = A.Dummy <int>().ThatIsInRange(0, 59),
                };

                return(result);
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var result = new IntervalSchedule()
                {
                    Interval = new TimeSpan(A.Dummy <long>().ThatIsInRange(0, 10000))
                };

                return(result);
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var result = new MonthlyScheduleInUtc()
                {
                    DaysOfMonth = new[]
                    {
                        A.Dummy <int>().ThatIsInRange(0, 28),
                        A.Dummy <int>().ThatIsInRange(0, 28),
                        A.Dummy <int>().ThatIsInRange(0, 28),
                        A.Dummy <int>().ThatIsInRange(0, 28),
                        A.Dummy <int>().ThatIsInRange(0, 28),
                    }.Distinct().ToArray(),
                    Hour   = A.Dummy <int>().ThatIsInRange(0, 23),
                    Minute = A.Dummy <int>().ThatIsInRange(0, 59),
                };

                return(result);
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var result = new WeeklyScheduleInUtc()
                {
                    DaysOfWeek = Some.Dummies <DayOfWeek>(3).ToArray(),
                    Hour       = A.Dummy <int>().ThatIsInRange(0, 23),
                    Minute     = A.Dummy <int>().ThatIsInRange(0, 59),
                };

                return(result);
            });

            AutoFixtureBackedDummyFactory.AddDummyCreator(
                () =>
            {
                var result = new YearlyScheduleInUtc()
                {
                    MonthsOfYear = Some.Dummies <MonthOfYear>(4).ToArray(),
                    DaysOfMonth  = new[]
                    {
                        A.Dummy <int>().ThatIsInRange(0, 28),
                        A.Dummy <int>().ThatIsInRange(0, 28),
                        A.Dummy <int>().ThatIsInRange(0, 28),
                        A.Dummy <int>().ThatIsInRange(0, 28),
                        A.Dummy <int>().ThatIsInRange(0, 28),
                    }.Distinct().ToArray(),
                    Hour   = A.Dummy <int>().ThatIsInRange(0, 23),
                    Minute = A.Dummy <int>().ThatIsInRange(0, 59),
                };

                return(result);
            });
        }
 public OperationIntervalSchedule(int interval)
 {
     _sheduler = new IntervalSchedule(interval);
     _sheduler.StartSchedule(OperationScheduleElapsed);
 }
 public void IntervalScheduleIntervalDefined_Valid()
 {
     var o = new IntervalSchedule { Interval = TimeSpan.FromHours(1) };
     Assert.NotNull(o);
     o.ThrowIfInvalid();
 }
Example #21
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool Exist(Period periodToCompare)
        {
            if (Schedule != null && Schedule.Count > 0)
            {
                foreach (Period period in Schedule)
                {
                    switch (periodToCompare.RepeatType)
                    {
                    case ScheduleRepeatType.ScheduleRepeatDaily:

                        ISchedule schedCurPer    = new IntervalSchedule(new TimeSpan(1, 0, 0, 0), period.End - period.Begin, period.Begin);
                        ISchedule schedPerToComp = new IntervalSchedule(new TimeSpan(1, 0, 0, 0), periodToCompare.End - periodToCompare.Begin, periodToCompare.Begin);

                        ISchedule overlap = new BoolNonIntersectionSchedule(schedCurPer, schedPerToComp);


                        IEnumerable <TimedEvent> eventsCurPer    = schedCurPer.GetRange(period.Begin, period.End);
                        IEnumerable <TimedEvent> eventsPerToComp = overlap.GetRange(periodToCompare.Begin, periodToCompare.End);

                        if (eventsCurPer.Any())
                        {
                            return(true);
                        }

                        break;


                    case ScheduleRepeatType.ScheduleRepeatWeekly:

                        ISchedule sched1 = new IntervalSchedule(new TimeSpan(7, 0, 0, 0), period.End - period.Begin, period.Begin);


                        IEnumerable <TimedEvent> events1 = sched1.GetRange(DateTime.Now.Add(new TimeSpan(-7, 0, 0, 0)), DateTime.Now.Add(new TimeSpan(7, 0, 0, 0)));

                        foreach (TimedEvent e in events1)
                        {
                            if (DateTime.Now >= e.StartTime && DateTime.Now <= e.EndTime)
                            {
                                return(true);
                            }
                        }

                        break;


                    case ScheduleRepeatType.ScheduleRepeatEverySecondWeek:

                        ISchedule sched2 = new IntervalSchedule(new TimeSpan(14, 0, 0, 0), period.End - period.Begin, period.Begin);

                        IEnumerable <TimedEvent> events2 = sched2.GetRange(DateTime.Now.Add(new TimeSpan(-14, 0, 0, 0)), DateTime.Now.Add(new TimeSpan(14, 0, 0, 0)));

                        foreach (TimedEvent e in events2)
                        {
                            if (DateTime.Now >= e.StartTime && DateTime.Now <= e.EndTime)
                            {
                                return(true);
                            }
                        }

                        break;

                    case ScheduleRepeatType.ScheduleRepeatEveryThirdWeek:

                        ISchedule sched3 = new IntervalSchedule(new TimeSpan(21, 0, 0, 0), period.End - period.Begin, period.Begin);

                        IEnumerable <TimedEvent> events3 = sched3.GetRange(DateTime.Now.Add(new TimeSpan(-21, 0, 0, 0)), DateTime.Now.Add(new TimeSpan(21, 0, 0, 0)));

                        foreach (TimedEvent e in events3)
                        {
                            if (DateTime.Now >= e.StartTime && DateTime.Now <= e.EndTime)
                            {
                                return(true);
                            }
                        }

                        break;

                    case ScheduleRepeatType.ScheduleRepeatMonthly:

                        ISchedule sched4 = new IntervalSchedule(new TimeSpan(DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month), 0, 0, 0), period.End - period.Begin, period.Begin);

                        IEnumerable <TimedEvent> events4 = sched4.GetRange(DateTime.Now.Add(new TimeSpan(-31, 0, 0, 0)), DateTime.Now.Add(new TimeSpan(31, 0, 0, 0)));

                        foreach (TimedEvent e in events4)
                        {
                            if (DateTime.Now >= e.StartTime && DateTime.Now <= e.EndTime)
                            {
                                return(true);
                            }
                        }

                        break;

                    default:
                        if (DateTime.Now >= period.Begin && DateTime.Now <= period.End)
                        {
                            return(true);
                        }
                        break;
                    }
                }
            }

            return(false);
        }
Example #22
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public bool IsOnTime(Period periodToCompare = null, bool compareWithCurrentDateTime = true)
        {
            if (Schedule != null && Schedule.Count > 0)
            {
                foreach (Period period in Schedule)
                {
                    switch (period.RepeatType)
                    {
                    case ScheduleRepeatType.ScheduleRepeatDaily:

                        ISchedule sched0 = new IntervalSchedule(new TimeSpan(1, 0, 0, 0), period.End - period.Begin, period.Begin);
                        IEnumerable <TimedEvent> events0 = sched0.GetRange(DateTime.Now.Add(new TimeSpan(-1, 0, 0, 0)), DateTime.Now.Add(new TimeSpan(1, 0, 0, 0)));

                        foreach (TimedEvent e in events0)
                        {
                            if (DateTime.Now >= e.StartTime && DateTime.Now <= e.EndTime)
                            {
                                return(true);
                            }
                        }

                        break;

                    case ScheduleRepeatType.ScheduleRepeatWeekly:

                        ISchedule sched1 = new IntervalSchedule(new TimeSpan(7, 0, 0, 0), period.End - period.Begin, period.Begin);


                        IEnumerable <TimedEvent> events1 = sched1.GetRange(DateTime.Now.Add(new TimeSpan(-7, 0, 0, 0)), DateTime.Now.Add(new TimeSpan(7, 0, 0, 0)));

                        foreach (TimedEvent e in events1)
                        {
                            if (DateTime.Now >= e.StartTime && DateTime.Now <= e.EndTime)
                            {
                                return(true);
                            }
                        }

                        break;


                    case ScheduleRepeatType.ScheduleRepeatEverySecondWeek:

                        ISchedule sched2 = new IntervalSchedule(new TimeSpan(14, 0, 0, 0), period.End - period.Begin, period.Begin);

                        IEnumerable <TimedEvent> events2 = sched2.GetRange(DateTime.Now.Add(new TimeSpan(-14, 0, 0, 0)), DateTime.Now.Add(new TimeSpan(14, 0, 0, 0)));

                        foreach (TimedEvent e in events2)
                        {
                            if (DateTime.Now >= e.StartTime && DateTime.Now <= e.EndTime)
                            {
                                return(true);
                            }
                        }

                        break;

                    case ScheduleRepeatType.ScheduleRepeatEveryThirdWeek:

                        ISchedule sched3 = new IntervalSchedule(new TimeSpan(21, 0, 0, 0), period.End - period.Begin, period.Begin);

                        IEnumerable <TimedEvent> events3 = sched3.GetRange(DateTime.Now.Add(new TimeSpan(-21, 0, 0, 0)), DateTime.Now.Add(new TimeSpan(21, 0, 0, 0)));

                        foreach (TimedEvent e in events3)
                        {
                            if (DateTime.Now >= e.StartTime && DateTime.Now <= e.EndTime)
                            {
                                return(true);
                            }
                        }

                        break;

                    case ScheduleRepeatType.ScheduleRepeatMonthly:

                        ISchedule sched4 = new IntervalSchedule(new TimeSpan(DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month), 0, 0, 0), period.End - period.Begin, period.Begin);

                        IEnumerable <TimedEvent> events4 = sched4.GetRange(DateTime.Now.Add(new TimeSpan(-31, 0, 0, 0)), DateTime.Now.Add(new TimeSpan(31, 0, 0, 0)));

                        foreach (TimedEvent e in events4)
                        {
                            if (DateTime.Now >= e.StartTime && DateTime.Now <= e.EndTime)
                            {
                                return(true);
                            }
                        }

                        break;

                    default:
                        if (DateTime.Now >= period.Begin && DateTime.Now <= period.End)
                        {
                            return(true);
                        }
                        break;
                    }
                }
            }

            return(false);
        }
        public void ShouldThrowArgumentOutOfRangeExceptionIfNextTimeIsMaxDate()
        {
            var schedule = new IntervalSchedule(DateTime.MinValue, TimeSpan.FromMinutes(1));

            Assert.Throws <ArgumentOutOfRangeException>(() => schedule.GetNextTime(DateTime.MaxValue));
        }