示例#1
0
        public void Test_TimeRange_Muti()
        {
            var values = new string[] { "01:00-13:25,16:00-19:25,18:00-22:22 * * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var date = DateTime.Now.Date;
                for (int i = 0; i < 100000; i++)
                {
                    var date1  = date.AddMinutes(i);
                    var datef1 = date1.Date.AddHours(1);
                    var datee1 = date1.Date.AddHours(13).AddMinutes(25);

                    var datef2 = date1.Date.AddHours(16);
                    var datee2 = date1.Date.AddHours(22).AddMinutes(22);
                    if ((date1 >= datef1 && date1 <= datee1) || (date1 >= datef2 && date1 <= datee2))
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }
示例#2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CrontabProcessor"/> class.
        /// </summary>
        /// <param name="crontabExpression">The crontab expression.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="SchedulerInitializationException"></exception>
        public CrontabProcessor(string crontabExpression)
        {
            if (string.IsNullOrEmpty(crontabExpression))
            {
                throw new ArgumentNullException();
            }

            Schedules       = new List <CrontabSchedule>();
            NextOccurrences = new List <DateTime>();

            var crontabExpressions = crontabExpression.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var expression in crontabExpressions)
            {
                var schedule = CrontabSchedule.TryParse(expression);

                if (schedule == null)
                {
                    throw new SchedulerInitializationException(
                              $"Crontab expression parsing failed, expression: '{expression}', full: '{crontabExpression}'");
                }

                Schedules.Add(schedule);
            }
        }
示例#3
0
        public void ScheduleJobRecurring(string jobID, string cronExpression, Action job)
        {
            var cnSchedule = CrontabSchedule.TryParse(cronExpression, new CrontabSchedule.ParseOptions { IncludingSeconds = false });
            if (cnSchedule == null)
            {
                throw new ArgumentException("Cron expression is wrong!");
            }

            // Add a new recurring job with the provided ID to the Jobmanager. The 5 seconds interval is only a stub and will be overridden.
            JobManager.AddJob(job, (x) => x.WithName(jobID).ToRunEvery(5).Seconds());
            // Retrieve the schedule from the newly created job
            var schedule = JobManager.AllSchedules.FirstOrDefault(x => x.Name == jobID);
            // Because FluentScheduler does not support cron expressions we have to override the default method that
            // calculates the next run with the appropriate method from the CrontabSchedule scheduler
            if (schedule != null)
            {
                var scheduleType = schedule.GetType();
                scheduleType
                  .GetProperty("CalculateNextRun", BindingFlags.NonPublic | BindingFlags.Instance)
                  .SetValue(schedule, (Func<DateTime, DateTime>)cnSchedule.GetNextOccurrence, null);
                scheduleType
                  .GetProperty("NextRun", BindingFlags.Public | BindingFlags.Instance)
                  .SetValue(schedule, cnSchedule.GetNextOccurrence(DateTime.Now));
            }
        }
示例#4
0
            public override Collection <Attribute> GetAttributes()
            {
                Collection <Attribute> attributes = new Collection <Attribute>();

                string schedule     = Context.GetMetadataValue <string>("schedule");
                bool   runOnStartup = Context.GetMetadataValue <bool>("runOnStartup");

                if (Utility.IsDynamic)
                {
                    // pre-resolve app setting specifiers
                    var resolver = new DefaultNameResolver();
                    schedule = resolver.ResolveWholeString(schedule);

                    var options = new CrontabSchedule.ParseOptions()
                    {
                        IncludingSeconds = true
                    };
                    if (CrontabSchedule.TryParse(schedule, options) == null)
                    {
                        throw new ArgumentException(string.Format("'{0}' is not a valid CRON expression.", schedule));
                    }
                }

                attributes.Add(new TimerTriggerAttribute(schedule)
                {
                    RunOnStartup = runOnStartup
                });

                return(attributes);
            }
示例#5
0
        public ScheduledJobRunner(Func <IJob> jobFactory, string schedule, ICacheClient cacheClient, ILoggerFactory loggerFactory = null)
        {
            _jobFactory = jobFactory;
            Schedule    = schedule;
            _logger     = loggerFactory?.CreateLogger <ScheduledJobRunner>() ?? NullLogger <ScheduledJobRunner> .Instance;

            _runner = new JobRunner(jobFactory, loggerFactory, runContinuous: false);

            _cronSchedule = CrontabSchedule.TryParse(schedule, s => s, e => {
                var ex = e();
                if (_logger.IsEnabled(LogLevel.Error))
                {
                    _logger.LogError(ex, "Error parsing schedule {Schedule}: {Message}", schedule, ex.Message);
                }
                return(null);
            });

            if (_cronSchedule == null)
            {
                throw new ArgumentException("Could not parse schedule.", nameof(schedule));
            }

            var dates    = _cronSchedule.GetNextOccurrences(SystemClock.UtcNow, DateTime.MaxValue).Take(2).ToList();
            var interval = TimeSpan.FromDays(1);

            if (dates.Count == 2)
            {
                interval = dates[1].Subtract(dates[0]);
            }

            _lockProvider = new ThrottlingLockProvider(cacheClient, 1, interval.Add(interval));
        }
示例#6
0
        protected void RegisterJob(string name, Type jobType, string cron)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException(nameof(cron));
            }
            if (jobType == null)
            {
                throw new ArgumentNullException(nameof(jobType));
            }
            if (cron == null)
            {
                throw new ArgumentNullException(nameof(cron));
            }

            CrontabSchedule.TryParse(cron);

            if (!typeof(IJob).GetTypeInfo().IsAssignableFrom(jobType))
            {
                throw new ArgumentException(
                          "Cron jobs should extend IJob.", nameof(jobType));
            }

            _entries.Add(new Entry(name, jobType, cron));
        }
            public override Collection <Attribute> GetAttributes()
            {
                Collection <Attribute> attributes = new Collection <Attribute>();

                string schedule     = Context.GetMetadataValue <string>("schedule");
                bool   runOnStartup = Context.GetMetadataValue <bool>("runOnStartup");
                bool   useMonitor   = Context.GetMetadataValue <bool>("useMonitor", true);

                if (_environment.IsWindowsConsumption())
                {
                    // pre-resolve app setting specifiers
                    schedule = _nameResolver.ResolveWholeString(schedule);

                    var options = new CrontabSchedule.ParseOptions()
                    {
                        IncludingSeconds = true
                    };
                    if (CrontabSchedule.TryParse(schedule, options) == null)
                    {
                        throw new ArgumentException(string.Format("'{0}' is not a valid CRON expression.", schedule));
                    }
                }

                attributes.Add(new TimerTriggerAttribute(schedule)
                {
                    RunOnStartup = runOnStartup,
                    UseMonitor   = useMonitor
                });

                return(attributes);
            }
示例#8
0
        public void Test_FT_End()
        {
            var values = new string[] { "20-59 * * * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var        date = DateTime.Now.Date;
                List <int> list = new List <int>()
                {
                    59
                };
                for (int i = 0; i < 100000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    if (date1.Minute >= 20 && date1.Minute <= 59)
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }
示例#9
0
        public void Test_Pre7_FTRE()
        {
            var values = new string[] { "43-12/7 * * * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var        date = DateTime.Now.Date;
                List <int> list = new List <int>()
                {
                    43, 50, 57, 4, 11
                };
                for (int i = 0; i < 100000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    if ((date1.Minute <= 12 || date1.Minute >= 43) && list.Contains(date1.Minute))
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }
        /// <summary>
        /// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts.
        /// </summary>
        /// <param name="args">Data passed by the start command.</param>
        protected override void OnStart(string[] args)
        {
            var taskClassType = typeof(T);

            _invokeMethodInfo = taskClassType.GetMethod(InvokeMethodName);

            if (_invokeMethodInfo == null)
            {
                throw new ServiceInitializationException(string.Format("Method {0} not found in class {1}", InvokeMethodName, taskClassType.Name));
            }

            _isParameterlessMethod = !_invokeMethodInfo.GetParameters().Any();

            if (!string.IsNullOrEmpty(Settings.CrontabExpression))
            {
                _schedule = CrontabSchedule.TryParse(Settings.CrontabExpression);

                if (_schedule == null)
                {
                    throw new ServiceInitializationException(string.Format("Crontab expression parsing failed, expression: '{0}'", Settings.CrontabExpression));
                }

                _nextOccurrence = _schedule.GetNextOccurrence(TimeProvider.Current.Now);

                _timer = new Timer(OnCronTimerTick, null, 1000, 60000);
            }
            else
            {
                _timer = new Timer(OnStartWork, null, 1000, Settings.ProcessingInterval * 1000);
            }

            base.OnStart(args);
        }
示例#11
0
        public static bool UpdateTaskFromSchedule(Event @event)
        {
            CrontabSchedule schedule = CrontabSchedule.TryParse(
                @event.EventFrequency.GetCronValue(),
                new CrontabSchedule.ParseOptions {
                IncludingSeconds = true
            });

            if (schedule != null)
            {
                if (crontabSchedule.ContainsKey(@event.Id))
                {
                    crontabSchedule[@event.Id] = schedule;
                    crontabNextRun[@event.Id]  = schedule.GetNextOccurrence(DateTime.UtcNow);
                }
                else
                {
                    crontabSchedule.Add(@event.Id, schedule);
                    crontabNextRun.Add(@event.Id, schedule.GetNextOccurrence(DateTime.UtcNow));
                }
            }
            else
            {
                crontabSchedule.Remove(@event.Id);
                crontabNextRun.Remove(@event.Id);
            }

            return(true);
        }
示例#12
0
        public void Test_Pre3_FTRE()
        {
            var values = new string[] { "* * 16-11/7 * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var        date = new DateTime(2000, 1, 1);
                List <int> list = new List <int>()
                {
                    16, 23, 30, 6
                };
                for (int i = 0; i < 10000000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    if (list.Contains(date1.Day))
                    {
                        Assert.True(schedule.Check(date1), date1.ToString());
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }
示例#13
0
        public void Test_Muti_FT()
        {
            var values = new string[] { "* * 1-5,7,11,21 * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var        date = new DateTime(2000, 1, 1);
                List <int> list = new List <int>()
                {
                    7, 11, 21
                };
                for (int i = 0; i < 10000000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    if (list.Contains(date1.Day) || (date1.Day >= 1 && date1.Day <= 5))
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1), date1.ToString());
                    }
                }
            }
        }
示例#14
0
        public void Test_Muti_End()
        {
            var values = new string[] { " * * 2,5,e * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var        date = new DateTime(2000, 1, 1);
                List <int> list = new List <int>()
                {
                    2, 5
                };
                for (int i = 0; i < 10000000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    if (list.Contains(date1.Day) || date1.AddDays(1).Day == 1)
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }
示例#15
0
        public void Test_Pre3_FTRE_Hour()
        {
            var values = new string[] { "* 13-5/3 1-5 * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var        date = DateTime.Now.Date;
                List <int> list = new List <int>()
                {
                    13, 16, 19, 22, 1, 4
                };
                for (int i = 0; i < 100000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    var hour  = date1.Hour;
                    var day   = date1.Day;
                    if (((date1.Hour >= 13 && day >= 1 && day <= 5) || (date1.Hour <= 5 && day >= 2 && day <= 6)) && list.Contains(hour))
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }
示例#16
0
        public void Test_Pre7_FTRE_Hour()
        {
            var values = new string[] { "43-12/7 3-6 * * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var date = DateTime.Now.Date;
                for (int i = 0; i < 100000; i++)
                {
                    var        date1 = date.AddMinutes(i);
                    List <int> list  = new List <int>()
                    {
                        43, 50, 57, 4, 11
                    };
                    var minute = date1.Minute;
                    var hour   = date1.Hour;
                    if (((minute >= 43 && hour >= 3 && hour <= 6) || (minute <= 12 && hour >= 4 && hour <= 7)) && list.Contains(minute))
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }
示例#17
0
        public void Test_Pre3_FTRE2()
        {
            var values = new string[] { "* 12-6/3 * * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var        date = DateTime.Now.Date;
                List <int> list = new List <int>()
                {
                    12, 15, 18, 21, 0, 3, 6
                };
                for (int i = 0; i < 100000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    if ((date1.Hour <= 6 || date1.Hour >= 12) && list.Contains(date1.Hour))
                    {
                        Assert.True(schedule.Check(date1), date1.ToString());
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }
示例#18
0
        public void Test_Muti_FT()
        {
            var values = new string[] { "* * * * 0-2,4,5", "* * * * 7-2,4,5" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var        date = DateTime.Now.Date;
                List <int> list = new List <int>()
                {
                    4, 5
                };
                for (int i = 0; i < 100000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    if (list.Contains((int)date1.DayOfWeek) || ((int)date1.DayOfWeek >= 0 && (int)date1.DayOfWeek <= 2))
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1), date1.ToString());
                    }
                }
            }
        }
示例#19
0
        static bool canRun(SchedulerContext context, JobItem jobItem, DateTime start)
        {
            if (jobItem.LeaseExpire.GetValueOrDefault() > start)
            {
                return(false);
            }
            if (jobItem.AlwaysRun)
            {
                return(true);
            }

            var lastRun = jobItem.LastRun.GetValueOrDefault();
            var cron    = CrontabSchedule.TryParse(jobItem.Cron);

            if (cron == null)
            {
                if (jobItem.LastRunResult != "CRON ERROR")
                {
                    postJob(context, jobItem, -1, "CRON ERROR", 0);
                }
                return(false);
            }

            var nextRun = cron.GetNextOccurrence(lastRun);

            if (nextRun > start)
            {
                return(false);
            }

            jobItem.NextRun = cron.GetNextOccurrence(start);
            return(true);
        }
示例#20
0
        public void Test_Pre3_FTRE()
        {
            var values = new string[] { "* * * * 5-3/2" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var        date = DateTime.Now.Date;
                List <int> list = new List <int>()
                {
                    5, 0, 2
                };
                for (int i = 0; i < 100000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    if (list.Contains((int)date1.DayOfWeek))
                    {
                        Assert.True(schedule.Check(date1), date1.ToString());
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }
示例#21
0
        public BedrockServiceWrapper(bool throwOnStart, bool throwOnStop, bool throwUnhandled)
        {
            try
            {
                _settings = AppSettings.Instance;


                bedrockServers = new List <BedrockServerWrapper>();
                _settings.ServerConfig.ForEach(t => bedrockServers.Add(new BedrockServerWrapper(t, _settings.BackupConfig)));
                if (_settings.BackupConfig.BackupOn && _settings.BackupConfig.BackupIntervalMinutes > 0)
                {
                    backupTimer          = new System.Timers.Timer(_settings.BackupConfig.BackupIntervalMinutes * 60000);
                    backupTimer.Elapsed += BackupTimer_Elapsed;
                    backupTimer.Start();
                }
                shed = CrontabSchedule.TryParse(_settings.BackupConfig.BackupIntervalCron);
                if (_settings.BackupConfig.BackupOn && shed != null)
                {
                    var nextRun = shed.GetNextOccurrence(DateTime.Now);
                    cronTimer          = new System.Timers.Timer((shed.GetNextOccurrence(DateTime.Now) - DateTime.Now).TotalMilliseconds);
                    cronTimer.Elapsed += CronTimer_Elapsed;
                    cronTimer.Start();
                }
            }
            catch (Exception e)
            {
                _log.Fatal("Error Instantiating BedrockServiceWrapper", e);
            }
        }
示例#22
0
        public IActionResult AddExecution(string id_repository, string nombre_job, string fecha_inicio, string cron_expression, string set = null, string codigo_objeto = null)
        {
            Guid     idRep       = Guid.Empty;
            DateTime fechaInicio = DateTime.Now;

            if (codigo_objeto != null && set == null)
            {
                return(BadRequest("falta el tipo de objeto"));
            }
            if (fecha_inicio != null)
            {
                try
                {
                    fechaInicio = DateTime.ParseExact(fecha_inicio, "dd/MM/yyyy HH:mm", null);
                }
                catch (Exception)
                {
                    return(BadRequest("fecha de inicio inválida"));
                }
            }

            try
            {
                idRep = new Guid(id_repository);
            }
            catch (Exception)
            {
                return(BadRequest("identificador invalido"));
            }
            bool validCronExpr = true;

            if (_cronApiService.ExistRecurringJob(nombre_job))
            {
                return(BadRequest("Ya existe una tarea con ese nombre"));
            }
            else if (string.IsNullOrEmpty(nombre_job))
            {
                return(BadRequest("El nombre no puede ser vacío"));
            }
            else
            {
                var correct = CrontabSchedule.TryParse(cron_expression);
                if (correct != null)
                {
                    _programingMethodsService.ProgramPublishRepositoryRecurringJob(idRep, nombre_job, cron_expression, fechaInicio, _configuration, set, codigo_objeto);
                }
                else
                {
                    validCronExpr = false;
                }
            }
            if (validCronExpr)
            {
                return(Ok());
            }
            else
            {
                return(BadRequest("invalid cron expression"));
            }
        }
示例#23
0
 public static void ValidarExpressaoCron(string expressao, string mensagem)
 {
     if (CrontabSchedule.TryParse(expressao) == null)
     {
         throw new InvalidOperationException(mensagem);
     }
 }
示例#24
0
        public void Test_End()
        {
            var values = new string[] { "* 23 * * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var        date = DateTime.Now.Date;
                List <int> list = new List <int>()
                {
                    23
                };
                for (int i = 0; i < 100000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    if (list.Contains(date1.Hour))
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }
示例#25
0
        public void Test_All4()
        {
            var values = new string[] { "*/5 */6 2-5 3,4,5,6 0,5", "0-59/5 0,6,12,18 2,3,4,5 3-6 0,5" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var date = DateTime.Now.Date;
                for (int i = 0; i < 1000000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    if (date1.Day >= 2 && date1.Day <= 5 && date1.Month >= 3 && date1.Month <= 6 &&
                        (date1.DayOfWeek == DayOfWeek.Sunday || date1.DayOfWeek == DayOfWeek.Friday) &&
                        date1.Minute % 5 == 0 &&
                        date1.Hour % 6 == 0
                        )
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1), date1.ToString());
                    }
                }
            }
        }
示例#26
0
        public void Test_Muti_FT()
        {
            var values = new string[] { "* 0-5,11,22 * * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var        date = DateTime.Now.Date;
                List <int> list = new List <int>()
                {
                    11, 22
                };
                for (int i = 0; i < 100000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    if (list.Contains(date1.Hour) || (date1.Hour >= 0 && date1.Hour <= 5))
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1), date1.ToString());
                    }
                }
            }
        }
        public DateTime?GetNextOccurrence(string scheduleSpec, DateTime baseTime)
        {
            int?year;

            ParseYearField(ref scheduleSpec, out year);

            ValueOrError <CrontabSchedule> sch = CrontabSchedule.TryParse(scheduleSpec);

            if (sch.IsError)
            {
                throw sch.Error;
            }

            DateTime endTime = DateTime.MaxValue;

            // If an year is specified, restrict the next occurrences to that specific year.
            if (year != null)
            {
                if (year.Value != baseTime.Year)
                {
                    baseTime = new DateTime(year.Value, 1, 1, 0, 0, 0, baseTime.Kind);
                }
                endTime = new DateTime(year.Value, 12, 31, 23, 59, 0, baseTime.Kind);
            }

            DateTime nextTime = sch.Value.GetNextOccurrence(baseTime, endTime);

            if (nextTime == endTime)
            {
                return(null);
            }

            return(nextTime);
        }
示例#28
0
        public void Test_FTRE_Hour()
        {
            var values = new string[] { "* 8-2 1-5 * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var date = DateTime.Now.Date;
                for (int i = 0; i < 100000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    var hour  = date1.Hour;
                    var day   = date1.Day;
                    if ((date1.Hour >= 8 && day >= 1 && day <= 5) || (date1.Hour <= 2 && day >= 2 && day <= 6))
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }
示例#29
0
        public CronTestModel TestCron([FromBody] CronViewModelBody body)
        {
            var model = new CronTestModel();

            try
            {
                var time   = DateTime.UtcNow;
                var result = CrontabSchedule.TryParse(body.Expression);
                for (int i = 0; i < 10; i++)
                {
                    var next = result.GetNextOccurrence(time);
                    model.Schedule.Add(next);
                    time = next;
                }
                model.Success = true;
                return(model);
            }
            catch (Exception)
            {
                return(new CronTestModel
                {
                    Message = $"CRON Expression {body.Expression} is not valid"
                });
            }
        }
示例#30
0
        public void Test_TimeRange()
        {
            var values = new string[] { "01:00-13:25 * * *" };

            foreach (var value in values)
            {
                var result = CrontabSchedule.TryParse(value, out CrontabSchedule schedule);
                Assert.True(result);
                var date = DateTime.Now.Date;
                for (int i = 0; i < 100000; i++)
                {
                    var date1 = date.AddMinutes(i);
                    var datef = date1.Date.AddHours(1);
                    var datee = date1.Date.AddHours(13).AddMinutes(25);
                    if (date1 >= datef && date1 <= datee)
                    {
                        Assert.True(schedule.Check(date1));
                    }
                    else
                    {
                        Assert.False(schedule.Check(date1));
                    }
                }
            }
        }