Exemplo n.º 1
0
 public void TestCronExpressionPassingMidnight()
 {
     CronExpression cronExpression = new CronExpression("0 15 23 * * ?");
     DateTimeOffset cal = new DateTime(2005, 6, 1, 23, 16, 0).ToUniversalTime();
     DateTimeOffset nextExpectedFireTime = new DateTime(2005, 6, 2, 23, 15, 0).ToUniversalTime();
     Assert.AreEqual(nextExpectedFireTime, cronExpression.GetTimeAfter(cal).Value);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Get the object to serialize when generating serialized file for future
        /// tests, and against which to validate deserialized object.
        /// </summary>
        /// <returns></returns>
        protected override object GetTargetObject()
        {
            CronExpression cronExpression = new CronExpression("0 15 10 * * ? 2005");
            cronExpression.TimeZone = testTimeZone;

            return cronExpression;
        }
Exemplo n.º 3
0
        public void TestCronExpressionLastDayOfMonth()
        {
            CronExpression cronExpression = new CronExpression("0 0 12 L * ?");
            int[] arrJuneDaysThatShouldFire = new int[] { 30 };
            List<int> juneDays = new List<int>(arrJuneDaysThatShouldFire);

            TestCorrectWeekFireDays(cronExpression, juneDays);
        }
        public void Should_be_able_to_create_an_all_inclusive_expression()
        {
            var date = new DateTime(2011, 1, 1, 0, 0, 0);
            var cron = new CronExpression("* * * * *", date);

            for (var i = 1; i < 121; i++)
            {
                Assert.AreEqual(date.AddMinutes(i), cron.NextOccurrence());
            }
        }
Exemplo n.º 5
0
 public void TestCronExpressionParsingIncorrectDayOfWeek()
 {
     // test failed before because of improper trimming
     try
     {
         string expr = string.Format(" * * * * * {0}", DateTime.Now.Year);
         CronExpression ce = new CronExpression(expr);
         ce.IsSatisfiedBy(DateTime.UtcNow.AddMinutes(2));
         Assert.Fail("Accepted wrong format");
     }
     catch (FormatException fe)
     {
         Assert.AreEqual("Day-of-Week values must be between 1 and 7", fe.Message);
     }
 }
        public void Should_be_able_to_get_week_days_across_month_boundary()
        {
            var date = new DateTime(2011, 1, 23, 0, 0, 0);
            var cron = new CronExpression("0 0 ? * 3,6", date);

            Assert.AreEqual(new DateTime(2011, 1, 25, 0, 0, 0), cron.NextOccurrence());
            Assert.AreEqual(new DateTime(2011, 1, 28, 0, 0, 0), cron.NextOccurrence());
            Assert.AreEqual(new DateTime(2011, 2, 1, 0, 0, 0), cron.NextOccurrence());
            Assert.AreEqual(new DateTime(2011, 2, 4, 0, 0, 0), cron.NextOccurrence());
            Assert.AreEqual(new DateTime(2011, 2, 8, 0, 0, 0), cron.NextOccurrence());

            date = new DateTime(2011, 2, 10, 0, 0, 0);
            cron = new CronExpression("0 0 ? * 3,6", date);

            Assert.AreEqual(new DateTime(2011, 2, 8, 0, 0, 0), cron.PreviousOccurrence());
            Assert.AreEqual(new DateTime(2011, 2, 4, 0, 0, 0), cron.PreviousOccurrence());
            Assert.AreEqual(new DateTime(2011, 2, 1, 0, 0, 0), cron.PreviousOccurrence());
            Assert.AreEqual(new DateTime(2011, 1, 28, 0, 0, 0), cron.PreviousOccurrence());
            Assert.AreEqual(new DateTime(2011, 1, 25, 0, 0, 0), cron.PreviousOccurrence());
        }
        public void Should_be_able_to_get_last_day_of_month_across_multiple_months()
        {
            var date = new DateTime(2011, 1, 1, 0, 0, 0);
            var cron = new CronExpression("0 0 L 1,2,5,6,9,12 *", date);

            Assert.AreEqual(new DateTime(2011, 1, 31, 0, 0, 0), cron.NextOccurrence());
            Assert.AreEqual(new DateTime(2011, 2, 28, 0, 0, 0), cron.NextOccurrence());
            Assert.AreEqual(new DateTime(2011, 5, 31, 0, 0, 0), cron.NextOccurrence());
            Assert.AreEqual(new DateTime(2011, 6, 30, 0, 0, 0), cron.NextOccurrence());
            Assert.AreEqual(new DateTime(2011, 9, 30, 0, 0, 0), cron.NextOccurrence());
            Assert.AreEqual(new DateTime(2011, 12, 31, 0, 0, 0), cron.NextOccurrence());

            date = new DateTime(2012, 1, 1, 0, 0, 0);
            cron = new CronExpression("0 0 L 1,2,5,6,9,12 *", date);

            Assert.AreEqual(new DateTime(2011, 12, 31, 0, 0, 0), cron.PreviousOccurrence());
            Assert.AreEqual(new DateTime(2011, 9, 30, 0, 0, 0), cron.PreviousOccurrence());
            Assert.AreEqual(new DateTime(2011, 6, 30, 0, 0, 0), cron.PreviousOccurrence());
            Assert.AreEqual(new DateTime(2011, 5, 31, 0, 0, 0), cron.PreviousOccurrence());
            Assert.AreEqual(new DateTime(2011, 2, 28, 0, 0, 0), cron.PreviousOccurrence());
            Assert.AreEqual(new DateTime(2011, 1, 31, 0, 0, 0), cron.PreviousOccurrence());
        }
Exemplo n.º 8
0
        public void TestIsSatisfiedBy()
        {
            CronExpression cronExpression = new CronExpression("0 15 10 * * ? 2005");

            DateTime cal = new DateTime(2005, 6, 1, 10, 15, 0).ToUniversalTime();
            Assert.IsTrue(cronExpression.IsSatisfiedBy(cal));

            cal = cal.AddYears(1);
            Assert.IsFalse(cronExpression.IsSatisfiedBy(cal));

            cal = new DateTime(2005, 6, 1, 10, 16, 0).ToUniversalTime();
            Assert.IsFalse(cronExpression.IsSatisfiedBy(cal));

            cal = new DateTime(2005, 6, 1, 10, 14, 0).ToUniversalTime();
            Assert.IsFalse(cronExpression.IsSatisfiedBy(cal));

            cronExpression = new CronExpression("0 15 10 ? * MON-FRI");

            // weekends
            cal = new DateTime(2007, 6, 9, 10, 15, 0).ToUniversalTime();
            Assert.IsFalse(cronExpression.IsSatisfiedBy(cal));
            Assert.IsFalse(cronExpression.IsSatisfiedBy(cal.AddDays(1)));
        }
Exemplo n.º 9
0
        public void ScheduleJob(SitecronJob job)
        {
            var jobDetail = CreateJobDetail(job);

            if (!string.IsNullOrEmpty(job.CronExpression))
            {
                if (CronExpression.IsValidExpression(job.CronExpression))
                {
                    Log.Info($"SiteCron - Job Loaded - Job Source: {job.JobSource} - {job.Name} - Type: {job.JobTypeSignature} USING Cron Expression: {job.CronExpression} Parameters: {job.Parameters} - Job ItemId:{job.ItemId}", this);
                    //IScheduleBuilder scheduleBuilder = CronScheduleBuilder.CronSchedule(job.CronExpression).InTimeZone(TimeZoneInfo.Utc);
                    var trigger = TriggerBuilder.Create()
                                  .WithIdentity(job.ItemId)
                                  .WithCronSchedule(job.CronExpression)
                                  .ForJob(jobDetail)
                                  .Build();
                    Scheduler.ScheduleJob(jobDetail, trigger);
                }
                else
                {
                    Log.Info($"SiteCron - Job NOT Loaded - Invalid CRON Expression - Job Source: {job.JobSource} - {job.Name} Type: {job.JobTypeSignature} USING Cron Expression: {job.CronExpression} Parameters: {job.Parameters} - Job ItemId:{job.ItemId}", this);
                }
            }

            if (job.ExecuteExactlyAtDateTime.Value != DateTime.MinValue)
            {
                Log.Info(
                    $"Sitecron - Job Loaded - Job Source: {job.JobSource} - {job.Name} - Type: {job.JobTypeSignature} USING ExecuteExactlyAtDateTime ServerTime: {DateUtil.ToServerTime(job.ExecuteExactlyAtDateTime.Value)} UTC: {job.ExecuteExactlyAtDateTime.Value.ToUniversalTime()} ServerTimeZone:{Settings.GetSetting(SitecronConstants.SettingsNames.ServerTimeZone, "master")} Parameters: {job.Parameters} - Job ItemId:{job.ItemId}", this);
                var startDateTime =
                    new DateTimeOffset(job.ExecuteExactlyAtDateTime.Value.ToUniversalTime());
                var trigger = TriggerBuilder.Create()
                              .WithIdentity(job.ItemId)
                              .StartAt(startDateTime)
                              .ForJob(jobDetail)
                              .Build();
                Scheduler.ScheduleJob(jobDetail, trigger);
            }
        }
 public async Task generatedailyCron(MouseEventArgs args)
 {
     if (dailyFormat != "")
     {
         dailyFormat = "";
     }
     if (CheckBoxeveryday == true)
     {
         var cron = CronExpression.EveryDayAt(Int32.Parse(hour), Int32.Parse(complexMinutes));
         dailyFormat = cron.ToString();
         try
         {
             var descriptCron = CronExpressionDescriptor.ExpressionDescriptor.GetDescription(cron);
         }
         catch (Exception e)
         {
             NotificationService.Notify(NotificationSeverity.Error, $"Error", $"Invalid cron expression");
             dailyFormat = "";
             throw;
         }
     }
     if (CheckBoxeveryweekday == true)
     {
         var cron = CronExpression.EveryWeekDayAt(Int32.Parse(hour), Int32.Parse(complexMinutes));
         dailyFormat = cron.ToString();
         try
         {
             var descriptCron = CronExpressionDescriptor.ExpressionDescriptor.GetDescription(cron);
         }
         catch (Exception e)
         {
             NotificationService.Notify(NotificationSeverity.Error, $"Error", $"Invalid cron expression");
             dailyFormat = "";
             throw;
         }
     }
 }
 public async Task generateadvancedmonthlyCron(MouseEventArgs args)
 {
     if (monthlyFormat != "")
     {
         monthlyFormat = "";
     }
     if (complexMonth == true)
     {
         var cron = CronExpression.EveryNMonth(day);
         monthlyFormat = cron;
         try
         {
             var descriptCron = CronExpressionDescriptor.ExpressionDescriptor.GetDescription(cron);
         }
         catch (Exception e)
         {
             NotificationService.Notify(NotificationSeverity.Error, $"Error", $"Invalid cron expression");
             monthlyFormat = "";
             throw;
         }
     }
     else
     {
         var cron = CronExpression.EverySpecificDayEveryNMonthAt(day, month, Int32.Parse(hour), Int32.Parse(complexMinutes));
         monthlyFormat = cron;
         try
         {
             var descriptCron = CronExpressionDescriptor.ExpressionDescriptor.GetDescription(cron);
         }
         catch (Exception e)
         {
             NotificationService.Notify(NotificationSeverity.Error, $"Error", $"Invalid cron expression");
             monthlyFormat = "";
             throw;
         }
     }
 }
Exemplo n.º 12
0
        public bool TryGetNextRun(DateTime from, out DateTime?next)
        {
            next = from;

            // from is before the first run time
            if (from < RunAt)
            {
                next = RunAt;
            }

            // Cron scheduled
            if (!string.IsNullOrEmpty(Cron))
            {
                var expression = CronExpression.Parse(Cron);
                next = expression.GetNextOccurrence(next.Value, true);
            }

            if (next > StopAfter)
            {
                next = null;
            }

            return(next != null);
        }
Exemplo n.º 13
0
        public static async Task <bool> ChangeProgramation(string cronExp)
        {
            if (!CronExpression.IsValidExpression(cronExp))
            {
                return(false);
            }

            IJobDetail job       = JobBuilder.Create <TareaQuartz>().Build();
            IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();

            ITrigger trigger = TriggerBuilder.Create()
                               .WithCronSchedule(cronExp)
                               .Build();

            if (jobKey != null)
            {
                await scheduler.DeleteJob(jobKey);
            }
            var next = await scheduler.ScheduleJob(job, trigger);

            DB.InsertaEvento("Change prog next at:" + next.ToString());
            jobKey = job.Key;
            return(next != null);
        }
Exemplo n.º 14
0
        public ScheduledJob(Type type)
        {
            if (!Utils.SupportsJob(type))
            {
                throw new ArgumentException("Type does not support IJob.", nameof(type));
            }

            var pattern = GetPattern(type);

            if (pattern == "@immediately")
            {
                _cron = null;
                _next = DateTime.UtcNow;
            }
            else if (pattern.StartsWith("@once "))
            {
                var value = pattern.Remove(0, 6);

                _cron = null;
                _next = DateTime.Parse(value);
            }
            else
            {
                _cron = CronExpression.Parse(pattern, CronFormat.IncludeSeconds);
                _next = _cron.GetNextOccurrence(DateTime.UtcNow);
            }

            Id              = Guid.NewGuid();
            Pattern         = pattern;
            Type            = type;
            Handler         = null;
            IsImmediately   = (pattern == "@immediately");
            IsOnce          = pattern.StartsWith("@once ");
            IsAnonymous     = false;
            OverlapHandling = GetOverlapHandling(type);
        }
Exemplo n.º 15
0
        private bool cronTest(string cronStr)
        {
            bool ret = true;

            try
            {
                CronExpression exp  = new CronExpression(cronStr);
                DateTime       dt   = DateTime.Now;
                DateTimeOffset dtof = new DateTimeOffset(dt);
                int            i    = 0;
                while (i < 5)
                {
                    dtof = (DateTimeOffset)exp.GetNextValidTimeAfter(dtof);
                    i++;
                }
            }
            catch (Exception e)
            {
                ret = false;
                logger.Error(string.Format("Corn表达式:'{0}'错误", cronStr), e);
            }

            return(ret);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Serialization constructor.
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        protected CronCalendar(SerializationInfo info, StreamingContext context) : base(info, context)
        {
            int version;

            try
            {
                version = info.GetInt32("version");
            }
            catch
            {
                version = 0;
            }

            switch (version)
            {
            case 0:
            case 1:
                cronExpression = (CronExpression)info.GetValue("cronExpression", typeof(CronExpression));
                break;

            default:
                throw new NotSupportedException("Unknown serialization version");
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// 修改Job
        /// </summary>
        public void Update(string id, JobInfoUpdateInputModel model)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new JIFException("Job 编号不能为空");
            }

            var job = Get(id);

            if (job == null)
            {
                throw new JIFException("Job 信息不存在");
            }


            if (string.IsNullOrWhiteSpace(model.Name) ||
                string.IsNullOrWhiteSpace(model.ServiceUrl) ||
                string.IsNullOrWhiteSpace(model.CronString))
            {
                throw new JIFException("Job 信息不完整");
            }

            if (!CronExpression.IsValidExpression(model.CronString))
            {
                throw new JIFException("Cro-expression 字符串不合规");
            }

            job.Name        = model.Name;
            job.Description = model.Description;
            job.ServiceUrl  = model.ServiceUrl;
            job.CronString  = model.CronString;

            _jobInfoRepository.Update(job);

            _schedulerContainer.UpdateScheduler(job.Id, job.CronString);
        }
Exemplo n.º 18
0
        /// <summary>
        ///
        /// </summary>
        public static void ScheduleRecurringJobs(IRepositoryMonitoringSettings monitoringSettings,
                                                 TelemetryClient telemetryClient)
        {
            if (monitoringSettings != null)
            {
                if (telemetryClient == null)
                {
                    throw new ArgumentNullException(nameof(telemetryClient));
                }

                for (int index = 0; index < monitoringSettings.RepositorySettings.Count; index++)
                {
                    var repositorySetting = monitoringSettings.RepositorySettings[index];
                    var expression        = repositorySetting.JobExecutionCron ?? "0 * * * *";
                    try
                    {
                        var _ = CronExpression.Parse(expression);
                    }
#pragma warning disable CA1031 // Do not catch general exception types
                    catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                    {
                        telemetryClient.TrackException(new InvalidOperationException(
                                                           $"Error while trying to convert expression {expression} as CRON", ex));
                        continue;
                    }

                    RecurringJob.RemoveIfExists(nameof(ScanRepositoryJob) + repositorySetting.JobName);
                    RecurringJob.AddOrUpdate <ScanRepositoryJob>(nameof(ScanRepositoryJob) + repositorySetting.JobName
                                                                 , job => job.Run(repositorySetting), expression);
                    telemetryClient.TrackRecurringJobScheduled(repositorySetting);
                }
            }

            RecurringJob.AddOrUpdate <SnapshotRepoCleanupJob>(nameof(SnapshotRepoCleanupJob), job => job.Run(), "0 * * * *");
        }
Exemplo n.º 19
0
        public static bool Init()
        {
            try
            {
                var cfg = (TextIndexCfgSectionHandler)ConfigurationManager.GetSection("fullTextIndex");
                ChangedCron = new CronExpression(cfg.ChangedCron);
                RemovedCron = new CronExpression(cfg.RemovedCron);
                MergeCron   = new CronExpression(cfg.MergeCron);
                Chunks      = cfg.Chunks;
                Dimension   = cfg.Dimension;
                Modules     = cfg.Modules
                              .Cast <TextIndexCfgModuleElement>()
                              .Select(e => new ModuleInfo(e.Name))
                              .ToList();
                DataPath = PrepareFolderPath(cfg.DataPath);
                ConfPath = PrepareFilePath(ConfName);

                var settings = InitConnectionSettings(cfg);
                if (settings.Host != "localhost")
                {
                    return(false);
                }

                var logPath = PrepareFolderPath(GetLog4NetPath());
                var connectionStringParts = ParseConnectionString(ConfigurationManager.ConnectionStrings["default"].ConnectionString);

                var shinxCfg = new SphinxCfg(connectionStringParts, DataPath, logPath, ConfPath, Modules);
                shinxCfg.Init();
            }
            catch (Exception e)
            {
                LogManager.GetLogger("ASC").Fatal("Error while init config", e);
                return(false);
            }
            return(true);
        }
Exemplo n.º 20
0
        public void TestIsSatisfiedBy()
        {
            CronExpression cronExpression = new CronExpression("0 15 10 * * ? 2005");

            DateTime cal = new DateTime(2005, 6, 1, 10, 15, 0).ToUniversalTime();

            Assert.IsTrue(cronExpression.IsSatisfiedBy(cal));

            cal = cal.AddYears(1);
            Assert.IsFalse(cronExpression.IsSatisfiedBy(cal));

            cal = new DateTime(2005, 6, 1, 10, 16, 0).ToUniversalTime();
            Assert.IsFalse(cronExpression.IsSatisfiedBy(cal));

            cal = new DateTime(2005, 6, 1, 10, 14, 0).ToUniversalTime();
            Assert.IsFalse(cronExpression.IsSatisfiedBy(cal));

            cronExpression = new CronExpression("0 15 10 ? * MON-FRI");

            // weekends
            cal = new DateTime(2007, 6, 9, 10, 15, 0).ToUniversalTime();
            Assert.IsFalse(cronExpression.IsSatisfiedBy(cal));
            Assert.IsFalse(cronExpression.IsSatisfiedBy(cal.AddDays(1)));
        }
Exemplo n.º 21
0
        public string Ins(SysJob Table_entity)
        {
            try
            {
                if (string.IsNullOrEmpty(Table_entity.MethodParams))
                {
                    throw new Exception("参数不能为空!");
                }

                if (string.IsNullOrEmpty(Table_entity.CronExpression))
                {
                    throw new Exception("cron表达式不能为空!");
                }

                if (Table_entity.Status == null)
                {
                    Table_entity.Status = "0";
                }
                if (Table_entity.Status == "0")
                {
                    CronExpression cronExpression = new CronExpression(Table_entity.CronExpression);
                    Table_entity.NextFireTime = cronExpression.GetNextValidTimeAfter(DateTime.Now).Value.ToLocalTime().DateTime;
                }

                Table_entity.JobGroup = Table_entity.JobName;
                _app.Ins(Table_entity);

                AddJob(Table_entity);
            }
            catch (Exception ex)
            {
                Result.Status  = false;
                Result.Message = ex.Message;
            }
            return(JsonHelper.Instance.Serialize(Result));
        }
Exemplo n.º 22
0
 public CronExpression ParseRange()
 {
     return(CronExpression.Parse("20-40 * * * *"));
 }
Exemplo n.º 23
0
 public CronExpression ParseStars()
 {
     return(CronExpression.Parse("* * * * *"));
 }
Exemplo n.º 24
0
        /// <summary>
        /// GetNextOccurrence
        /// </summary>
        /// <param name="expression">cron expression</param>
        /// <param name="period">next period</param>
        /// <param name="timeZoneInfo">timeZoneInfo</param>
        /// <returns>next occurrence times</returns>
        public static IEnumerable <DateTimeOffset> GetNextOccurrences(this CronExpression expression, TimeSpan period, TimeZoneInfo timeZoneInfo)
        {
            var utcNow = DateTime.UtcNow;

            return(expression.GetOccurrences(utcNow, utcNow.Add(period), timeZoneInfo));
        }
Exemplo n.º 25
0
        public void TestCronExpressionPassingYear()
        {
            DateTimeOffset start = new DateTime(2007, 12, 1, 23, 59, 59).ToUniversalTime();

            CronExpression ce = new CronExpression("0 55 15 1 * ?");
            DateTimeOffset expected = new DateTime(2008, 1, 1, 15, 55, 0).ToUniversalTime();
            DateTimeOffset d = ce.GetNextValidTimeAfter(start).Value;
            Assert.AreEqual(expected, d, "Got wrong date and time when passed year");
        }
Exemplo n.º 26
0
 public CronTrigger(CronExpression expression, TimeSpan fireOffset)
     : base(fireOffset)
 {
     _expression = expression;
 }
Exemplo n.º 27
0
        private static void TestCorrectWeekFireDays(CronExpression cronExpression, IList<int> correctFireDays)
        {
            List<int> fireDays = new List<int>();

            DateTime cal = new DateTime(2007, 6, 1, 11, 0, 0).ToUniversalTime();
            for (int i = 0; i < DateTime.DaysInMonth(2007, 6); ++i)
            {
                DateTimeOffset? nextFireTime = cronExpression.GetTimeAfter(cal);
                if (!fireDays.Contains(nextFireTime.Value.Day) && nextFireTime.Value.Month == 6)
                {
                    // next fire day may be monday for several days..
                    fireDays.Add(nextFireTime.Value.Day);
                }
                cal = cal.AddDays(1);
            }
            // check rite dates fired
            for (int i = 0; i < fireDays.Count; ++i)
            {
                int idx = correctFireDays.IndexOf(fireDays[i]);
                Assert.Greater(idx, -1,
                               string.Format("CronExpression evaluated true for {0} even when it shouldn't have", fireDays[i]));
                correctFireDays.RemoveAt(idx);
            }

            // check that all fired
            Assert.IsTrue(correctFireDays.Count == 0, string.Format("CronExpression did not evaluate true for all expected days (count: {0}).", correctFireDays.Count));
        }
Exemplo n.º 28
0
 public void TestQRTZNET152()
 {
     CronExpression expression = new CronExpression("0 5 13 5W 1-12 ?");
     DateTimeOffset test = new DateTimeOffset(2009, 3, 8, 0, 0, 0, TimeSpan.Zero);
     DateTimeOffset d = expression.GetNextValidTimeAfter(test).Value;
     Assert.AreEqual(new DateTimeOffset(2009, 4, 6, 13, 5, 0, TimeZoneInfo.Local.GetUtcOffset(test)).ToUniversalTime(), d);
     d = expression.GetNextValidTimeAfter(d).Value;
     Assert.AreEqual(new DateTimeOffset(2009, 5, 5, 13, 5, 0, TimeZoneInfo.Local.GetUtcOffset(d)), d);
 }
Exemplo n.º 29
0
 public override int GetHashCode()
 {
     return(string.Format("{0}_{1}_{2}", CronExpression.GetHashCode(), Payload.GetHashCode(), Enable.GetHashCode()).GetHashCode());
 }
Exemplo n.º 30
0
 /// <summary>
 /// Sets the cron expression for the calendar to a new value.
 /// </summary>
 /// <param name="expression">The expression.</param>
 public void SetCronExpressionString(string expression)
 {
     CronExpression newExp = new CronExpression(expression);
     cronExpression = newExp;
 }
Exemplo n.º 31
0
        public void TestDaylightSavingsDoesNotMatchAnHourBefore2()
        {
            //another case
            TimeZoneInfo est = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time");
            CronExpression expression = new CronExpression("0 0 0 ? * THU");
            expression.TimeZone = est;

            DateTimeOffset startTime = new DateTimeOffset(2012, 11, 4, 0, 0, 0, TimeSpan.Zero);

            var actualTime = expression.GetTimeAfter(startTime);
            DateTimeOffset expected = new DateTimeOffset(2012, 11, 8, 0, 0, 0, TimeSpan.FromHours(-5));
            Assert.AreEqual(expected, actualTime);
        }
Exemplo n.º 32
0
 public void TestDaylightSaving_QRTZNETZ186()
 {
     CronExpression expression = new CronExpression("0 15 * * * ?");
     if (!TimeZoneInfo.Local.SupportsDaylightSavingTime)
     {
         return;
     }
     var daylightChange = TimeZone.CurrentTimeZone.GetDaylightChanges(2012);
     DateTimeOffset before = daylightChange.Start.ToUniversalTime().AddMinutes(-5); // keep outside the potentially undefined interval
     DateTimeOffset? after = expression.GetNextValidTimeAfter(before);
     Assert.IsTrue(after.HasValue);
     DateTimeOffset expected = daylightChange.Start.Add(daylightChange.Delta).AddMinutes(15).ToUniversalTime();
     Assert.AreEqual(expected, after.Value);
 }
Exemplo n.º 33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CronCalendar"/> class.
 /// </summary>
 /// <param name="expression">a string representation of the desired cron expression</param>
 public CronCalendar(string expression)
 {
     cronExpression = new CronExpression(expression);
 }
Exemplo n.º 34
0
 public CronExpression ParseComplex()
 {
     return(CronExpression.Parse("*/10 12-20 ? DEC 3"));
 }
Exemplo n.º 35
0
 /// <summary>
 /// Create a <see cref="CronCalendar" /> with the given cron expression and 
 /// <see cref="BaseCalendar" />. 
 /// </summary>
 /// <param name="baseCalendar">
 /// the base calendar for this calendar instance 
 /// see BaseCalendar for more information on base
 /// calendar functionality
 /// </param>
 /// <param name="expression">a string representation of the desired cron expression</param>
 /// <param name="timeZone"></param>
 public CronCalendar(ICalendar baseCalendar, string expression, TimeZoneInfo timeZone)
     : base(baseCalendar, timeZone)
 {
     cronExpression = new CronExpression(expression);
 }
Exemplo n.º 36
0
 protected CronJobService(string cronExpression, TimeZoneInfo timeZoneInfo)
 {
     _expression   = CronExpression.Parse(cronExpression);
     _timeZoneInfo = timeZoneInfo;
 }
Exemplo n.º 37
0
 public void TestYearChange()
 {
     // QRTZNET-85
     CronExpression cronExpression = new CronExpression("0 12 4 ? * 3");
     cronExpression.GetNextValidTimeAfter(new DateTime(2007, 12, 28));
 }
Exemplo n.º 38
0
        /// <summary>
        /// 添加一个计划任务(映射程序集指定IJob实现类)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tasksQz"></param>
        /// <returns></returns>
        public async Task <MessageModel <string> > AddScheduleJobAsync(TasksQz tasksQz)
        {
            var result = new MessageModel <string>();

            try
            {
                if (tasksQz != null)
                {
                    JobKey jobKey = new JobKey(tasksQz.Id.ToString(), tasksQz.JobGroup);
                    if (await _scheduler.Result.CheckExists(jobKey))
                    {
                        result.success = false;
                        result.msg     = $"该任务计划已经在执行:【{tasksQz.Name}】,请勿重复启动!";
                        return(result);
                    }
                    #region 设置开始时间和结束时间

                    if (tasksQz.BeginTime == null)
                    {
                        tasksQz.BeginTime = DateTime.Now;
                    }
                    DateTimeOffset starRunTime = DateBuilder.NextGivenSecondDate(tasksQz.BeginTime, 1);//设置开始时间
                    if (tasksQz.EndTime == null)
                    {
                        tasksQz.EndTime = DateTime.MaxValue.AddDays(-1);
                    }
                    DateTimeOffset endRunTime = DateBuilder.NextGivenSecondDate(tasksQz.EndTime, 1);//设置暂停时间

                    #endregion

                    #region 通过反射获取程序集类型和类

                    Assembly assembly = Assembly.Load(new AssemblyName(tasksQz.AssemblyName));
                    Type     jobType  = assembly.GetType(tasksQz.AssemblyName + "." + tasksQz.ClassName);

                    #endregion
                    //判断任务调度是否开启
                    if (!_scheduler.Result.IsStarted)
                    {
                        await StartScheduleAsync();
                    }

                    //传入反射出来的执行程序集
                    IJobDetail job = new JobDetailImpl(tasksQz.Id.ToString(), tasksQz.JobGroup, jobType);
                    job.JobDataMap.Add("JobParam", tasksQz.JobParams);
                    ITrigger trigger;

                    #region 泛型传递
                    //IJobDetail job = JobBuilder.Create<T>()
                    //    .WithIdentity(sysSchedule.Name, sysSchedule.JobGroup)
                    //    .Build();
                    #endregion

                    if (tasksQz.Cron != null && CronExpression.IsValidExpression(tasksQz.Cron) && tasksQz.TriggerType > 0)
                    {
                        trigger = CreateCronTrigger(tasksQz);
                    }
                    else
                    {
                        trigger = CreateSimpleTrigger(tasksQz);
                    }
                    // 告诉Quartz使用我们的触发器来安排作业
                    await _scheduler.Result.ScheduleJob(job, trigger);

                    //await Task.Delay(TimeSpan.FromSeconds(120));
                    //await Console.Out.WriteLineAsync("关闭了调度器!");
                    //await _scheduler.Result.Shutdown();
                    result.success = true;
                    result.msg     = $"启动任务:【{tasksQz.Name}】成功";
                    return(result);
                }
                else
                {
                    result.success = false;
                    result.msg     = $"任务计划不存在:【{tasksQz.Name}】";
                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Serialization constructor.
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        protected CronCalendar(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            int version;
            try
            {
                version = info.GetInt32("version");
            }
            catch
            {
                version = 0;
            }

            switch (version)
            {
                case 0:
                case 1:
                    cronExpression = (CronExpression) info.GetValue("cronExpression", typeof (CronExpression));
                    break;
                default:
                    throw new NotSupportedException("Unknown serialization version");
            }
        }
Exemplo n.º 40
0
 protected CronScheduleBuilder(CronExpression cronExpression)
 {
     this.cronExpression = cronExpression ?? throw new ArgumentNullException("cronExpression", "cronExpression cannot be null");
 }
Exemplo n.º 41
0
 public CronTrigger(CronExpression expression)
     : this(expression, TimeSpan.Zero)
 {
 }
Exemplo n.º 42
0
        public void TestGetTimeAfter_QRTZNET149()
        {
            CronExpression expression = new CronExpression("0 0 0 29 * ?");
            DateTimeOffset? after = expression.GetNextValidTimeAfter(new DateTime(2009, 1, 30, 0, 0, 0).ToUniversalTime());
            Assert.IsTrue(after.HasValue);
            Assert.AreEqual(new DateTime(2009, 3, 29, 0, 0, 0).ToUniversalTime(), after.Value.DateTime);

            after = expression.GetNextValidTimeAfter(new DateTime(2009, 12, 30).ToUniversalTime());
            Assert.IsTrue(after.HasValue);
            Assert.AreEqual(new DateTime(2010, 1, 29, 0, 0, 0).ToUniversalTime(), after.Value.DateTime);
        }
Exemplo n.º 43
0
        /// <summary>
        /// 检查参数是否符合要求
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        private async Task <bool> CheckScheduleEntityParam(ScheduleEntityParam entity, ResponseModel <string> result)
        {
            //检查任务是否已存在
            var jobKey = new JobKey(entity.JobName, entity.JobGroup);

            if (await Scheduler.CheckExists(jobKey))
            {
                result.Fail("调度任务已存在", "");
                return(false);
            }

            // 检查Cron表达式
            if (entity.TriggerType == TriggerTypeEnum.Cron)
            {
                if (!CronExpression.IsValidExpression(entity.Cron))
                {
                    result.Fail("Cron表达式不正确");
                    return(false);
                }
            }

            // 检查请求头格式是否正确
            if (entity.JobType == JobTypeEnum.Http && entity.Headers.IsNotNullOrEmpty())
            {
                try
                {
                    // 判断是否能转成字典格式 数据是否正确
                    entity.Headers.ToObject <Dictionary <string, string> >();
                }
                catch
                {
                    result.Fail(ResponseCode.DataFormatError, "请求头参数格式错误,json字典格式", "");
                    return(false);
                }
            }

            // 检查通知接收邮箱是否正确
            if (entity.MailMessage != MailMessageEnum.None)
            {
                if (entity.NotifyEmail.IsNullOrEmpty())
                {
                    result.Fail(ResponseCode.DataFormatError, "通知邮箱不能为空", "");
                    return(false);
                }

                var notifyEmails = entity.NotifyEmail.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                var sb           = new List <string>();
                notifyEmails.ForEach(notifyEmail =>
                {
                    if (!notifyEmail.IsEmail())
                    {
                        sb.Add($"邮箱[{notifyEmail}]格式不正确");
                    }
                });
                if (sb.Count > 0)
                {
                    result.Fail(ResponseCode.DataFormatError, string.Join(@"\n", sb), "");
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 44
0
 public void TestHourShift()
 {
     // cronexpression that fires every 5 seconds
     CronExpression cronExpression = new CronExpression("0/5 * * * * ?");
     DateTimeOffset cal = new DateTimeOffset(2005, 6, 1, 1, 59, 55, TimeSpan.Zero);
     DateTimeOffset nextExpectedFireTime = new DateTimeOffset(2005, 6, 1, 2, 0, 0, TimeSpan.Zero);
     Assert.AreEqual(nextExpectedFireTime, cronExpression.GetTimeAfter(cal).Value);
 }
Exemplo n.º 45
0
 public CronExpression ParseMacroDaily()
 {
     return(CronExpression.Parse("@daily"));
 }
Exemplo n.º 46
0
        public void TestLastDayOffset()
        {
            CronExpression cronExpression = new CronExpression("0 15 10 L-2 * ? 2010");

            DateTime cal = new DateTime(2010, 10, 29, 10, 15, 0).ToUniversalTime(); // last day - 2
            Assert.IsTrue(cronExpression.IsSatisfiedBy(cal));

            cal = new DateTime(2010, 10, 28, 10, 15, 0).ToUniversalTime();
            Assert.IsFalse(cronExpression.IsSatisfiedBy(cal));

            cronExpression = new CronExpression("0 15 10 L-5W * ? 2010");

            cal = new DateTime(2010, 10, 26, 10, 15, 0).ToUniversalTime(); // last day - 5
            Assert.IsTrue(cronExpression.IsSatisfiedBy(cal));

            cronExpression = new CronExpression("0 15 10 L-1 * ? 2010");

            cal = new DateTime(2010, 10, 30, 10, 15, 0).ToUniversalTime(); // last day - 1
            Assert.IsTrue(cronExpression.IsSatisfiedBy(cal));

            cronExpression = new CronExpression("0 15 10 L-1W * ? 2010");

            cal = new DateTime(2010, 10, 29, 10, 15, 0).ToUniversalTime(); // nearest weekday to last day - 1 (29th is a friday in 2010)
            Assert.IsTrue(cronExpression.IsSatisfiedBy(cal));
        }
Exemplo n.º 47
0
 public CronExpression ParseNumber()
 {
     return(CronExpression.Parse("20 * * * *"));
 }
Exemplo n.º 48
0
 public void TestMonthShift()
 {
     // QRTZNET-28
     CronExpression cronExpression = new CronExpression("* * 1 * * ?");
     DateTimeOffset cal = new DateTime(2005, 7, 31, 22, 59, 57).ToUniversalTime();
     DateTimeOffset nextExpectedFireTime = new DateTime(2005, 8, 1, 1, 0, 0).ToUniversalTime();
     Assert.AreEqual(nextExpectedFireTime, cronExpression.GetTimeAfter(cal).Value);
 }
Exemplo n.º 49
0
 public CronExpression ParseList()
 {
     return(CronExpression.Parse("20,30,40,50 * * * *"));
 }
Exemplo n.º 50
0
        public void TestNthWeekDayPassingMonth()
        {
            CronExpression ce = new CronExpression("0 30 10-13 ? * FRI#3");
            DateTime start = new DateTime(2008, 12, 19, 0, 0, 0);
            for (int i = 0; i < 200; ++i)
            {
                bool shouldFire = (start.Hour >= 10 && start.Hour <= 13 && start.Minute == 30 && (start.DayOfWeek == DayOfWeek.Wednesday || start.DayOfWeek == DayOfWeek.Friday));
                shouldFire = shouldFire && start.Day > 15 && start.Day < 28;

                bool satisfied = ce.IsSatisfiedBy(start.ToUniversalTime());
                Assert.AreEqual(shouldFire, satisfied);

                // cycle with half hour precision
                start = start.AddHours(0.5);
            }
        }
Exemplo n.º 51
0
 public CronExpression ParseMacroEverySecond()
 {
     return(CronExpression.Parse("@every_second"));
 }
Exemplo n.º 52
0
 /// <summary>
 /// Create a <see cref="CronCalendar" /> with the given cron expression and 
 /// <see cref="BaseCalendar" />. 
 /// </summary>
 /// <param name="baseCalendar">
 /// the base calendar for this calendar instance 
 /// see BaseCalendar for more information on base
 /// calendar functionality
 /// </param>
 /// <param name="expression">a string representation of the desired cron expression</param>
 public CronCalendar(ICalendar baseCalendar, string expression)
     : base(baseCalendar)
 {
     cronExpression = new CronExpression(expression);
 }
Exemplo n.º 53
0
        /// <summary>
        /// Checks whether a cron expression is valid or not.
        /// </summary>
        /// <param name="expression">Cron expression</param>
        /// <returns></returns>
        public static bool IsCronExpressionValid(string expression)
        {
            bool res = CronExpression.IsValidExpression(expression);

            return(res);
        }
Exemplo n.º 54
0
        public void TestCronExpressionWeekdaysFriday()
        {
            CronExpression cronExpression = new CronExpression("0 0 12 ? * FRI");
            int[] arrJuneDaysThatShouldFire =
                new int[] { 1, 8, 15, 22, 29 };
            List<int> juneDays = new List<int>(arrJuneDaysThatShouldFire);

            TestCorrectWeekFireDays(cronExpression, juneDays);
        }
Exemplo n.º 55
0
 /// <summary>
 /// 校验字符串是否为正确的Cron表达式
 /// </summary>
 /// <param name="cronExpression">带校验表达式</param>
 /// <returns></returns>
 public bool ValidExpression(string cronExpression)
 {
     return(CronExpression.IsValidExpression(cronExpression));
 }
Exemplo n.º 56
0
        public void TestCronExpressionWeekdaysMonFri()
        {
            CronExpression cronExpression = new CronExpression("0 0 12 ? * MON-FRI");
            int[] arrJuneDaysThatShouldFire =
                new int[] { 1, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 18, 19, 20, 22, 21, 25, 26, 27, 28, 29 };
            List<int> juneDays = new List<int>(arrJuneDaysThatShouldFire);

            TestCorrectWeekFireDays(cronExpression, juneDays);
        }
Exemplo n.º 57
0
 /// <summary>
 /// Create a CronScheduleBuilder with the given cron-expression.
 /// </summary>
 /// <param name="cronExpression">the cron expression to base the schedule on.</param>
 /// <returns>the new CronScheduleBuilder</returns>
 /// <seealso cref="CronExpression" />
 public static CronScheduleBuilder CronSchedule(CronExpression cronExpression)
 {
     return(new CronScheduleBuilder(cronExpression));
 }
Exemplo n.º 58
0
 public void TestCronExpressionWithExtraWhiteSpace()
 {
     // test failed before because of improper trimming
     string expr = " 30 *   * * * ?  ";
     CronExpression calendar = new CronExpression(expr);
     Assert.IsFalse(calendar.IsSatisfiedBy(DateTime.Now.AddMinutes(2)), "Time was included");
 }
Exemplo n.º 59
0
 /// <summary>
 /// Create a CronScheduleBuilder with the given cron-expression - which
 /// is presumed to b e valid cron expression (and hence only a RuntimeException
 /// will be thrown if it is not).
 /// </summary>
 /// <remarks>
 /// </remarks>
 /// <param name="cronExpression">the cron expression to base the schedule on.</param>
 /// <returns>the new CronScheduleBuilder</returns>
 /// <seealso cref="CronExpression" />
 public static CronScheduleBuilder CronSchedule(string cronExpression)
 {
     CronExpression.ValidateExpression(cronExpression);
     return(CronScheduleNoParseException(cronExpression));
 }
Exemplo n.º 60
0
 public void TestFormatExceptionWildCardDayOfMonthAndSpecifiedDayOfWeek()
 {
     CronExpression cronExpression = new CronExpression("0 0 * * * 4");
 }