Ejemplo n.º 1
0
        public Task Execute(IJobExecutionContext context)
        {
            return(Task.Run(async() =>
            {
                TData obj = new TData();
                long jobId = 0;
                JobDataMap jobData = null;
                AutoJobEntity dbJobEntity = null;
                try
                {
                    jobData = context.JobDetail.JobDataMap;
                    jobId = jobData["Id"].ParseToLong();
                    // 获取数据库中的任务
                    dbJobEntity = await autoJobService.GetEntity(jobId);
                    if (dbJobEntity != null)
                    {
                        if (dbJobEntity.JobStatus == StatusEnum.Yes.ParseToInt())
                        {
                            CronTriggerImpl trigger = context.Trigger as CronTriggerImpl;
                            if (trigger != null)
                            {
                                if (trigger.CronExpressionString != dbJobEntity.CronExpression)
                                {
                                    // 更新任务周期
                                    trigger.CronExpressionString = dbJobEntity.CronExpression;
                                    await JobScheduler.GetScheduler().RescheduleJob(trigger.Key, trigger);
                                }

                                #region 执行任务
                                switch (context.JobDetail.Key.Name)
                                {
                                case "数据库备份":
                                    obj = await new DatabasesBackupJob().Start();
                                    break;
                                }
                                #endregion
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    obj.Message = ex.GetOriginalException().Message;
                    LogHelper.Error(ex);
                }

                try
                {
                    if (dbJobEntity != null)
                    {
                        if (dbJobEntity.JobStatus == StatusEnum.Yes.ParseToInt())
                        {
                            #region 更新下次运行时间
                            await autoJobService.SaveForm(new AutoJobEntity
                            {
                                Id = dbJobEntity.Id,
                                NextStartTime = context.NextFireTimeUtc.Value.DateTime.AddHours(8)
                            });
                            #endregion

                            #region 记录执行状态
                            await autoJobLogService.SaveForm(new AutoJobLogEntity
                            {
                                JobGroupName = context.JobDetail.Key.Group,
                                JobName = context.JobDetail.Key.Name,
                                LogStatus = obj.Tag,
                                Remark = obj.Message
                            });
                            #endregion
                        }
                    }
                }
                catch (Exception ex)
                {
                    obj.Message = ex.GetOriginalException().Message;
                    LogHelper.Error(ex);
                }
            }));
        }
Ejemplo n.º 2
0
        public async Task CronTrigger_AfterTriggerUpdate_Retains_Cron_Type()
        {
            //Arrange
            var cronTriggerImpl = new CronTriggerImpl("Trigger", "Trigger.Group", "JobName", "JobGroup", "0 15 23 * * ?");

            cronTriggerImpl.CalendarName       = "calName";
            cronTriggerImpl.MisfireInstruction = 1;
            cronTriggerImpl.Description        = "Description";
            cronTriggerImpl.SetPreviousFireTimeUtc(new DateTimeOffset(new DateTime(2010, 1, 1)));
            cronTriggerImpl.SetNextFireTimeUtc(new DateTimeOffset(new DateTime(2010, 2, 1)));
            cronTriggerImpl.JobKey   = new JobKey("JobKey", "JobKeyGroup");
            cronTriggerImpl.Priority = 1;

            var dbProvider = A.Fake <IDbProvider>();
            var dbCommand  = A.Fake <DbCommand>();
            var dataParameterCollection = A.Fake <DbParameterCollection>();

            A.CallTo(() => dbProvider.CreateCommand()).Returns(dbCommand);
            Func <DbParameter> dataParam = () => new SqlParameter();

            A.CallTo(dbProvider)
            .Where(x => x.Method.Name == "CreateDbParameter")
            .WithReturnType <DbParameter>()
            .ReturnsLazily(dataParam);

            A.CallTo(dbCommand)
            .Where(x => x.Method.Name == "CreateDbParameter")
            .WithReturnType <DbParameter>()
            .ReturnsLazily(dataParam);

            var dataParameterCollectionOutputs = new List <object>();

            A.CallTo(() => dataParameterCollection.Add(A <object> ._)).Invokes(x =>
            {
                dataParameterCollectionOutputs.Add(x.Arguments.Single());
            });

            A.CallTo(dbCommand)
            .Where(x => x.Method.Name == "get_DbParameterCollection")
            .WithReturnType <DbParameterCollection>()
            .Returns(dataParameterCollection);

            var metaData = A.Fake <DbMetadata>();

            A.CallTo(() => dbProvider.Metadata).Returns(metaData);

            Func <string, string> paramFunc = x => x;

            A.CallTo(() => metaData.GetParameterName(A <string> .Ignored)).ReturnsLazily(paramFunc);

            DelegateInitializationArgs args = new DelegateInitializationArgs();

            args.TablePrefix    = "QRTZ_";
            args.InstanceName   = "TESTSCHED";
            args.InstanceId     = "INSTANCE";
            args.DbProvider     = dbProvider;
            args.TypeLoadHelper = new SimpleTypeLoadHelper();

            var adoDelegate = new StdAdoDelegate();

            adoDelegate.Initialize(args);

            var dbConnection = new StubConnection();
            var conn         = new ConnectionAndTransactionHolder(dbConnection, null);
            var jobDetail    = A.Fake <IJobDetail>();
            var jobDataMap   = new JobDataMap();

            jobDataMap.ClearDirtyFlag();
            cronTriggerImpl.JobDataMap = jobDataMap;

            //Act
            await adoDelegate.UpdateTrigger(conn, cronTriggerImpl, "state", jobDetail);

            //Assert
            var resultDataParameters = dataParameterCollectionOutputs.Select(x => x as IDataParameter).Where(x => x.ParameterName == "triggerType").FirstOrDefault();

            Assert.AreEqual("CRON", resultDataParameters.Value);
        }
Ejemplo n.º 3
0
        public async Task Test(IScheduler scheduler, bool clearJobs, bool scheduleJobs)
        {
            try
            {
                if (clearJobs)
                {
                    await scheduler.Clear();
                }

                if (scheduleJobs)
                {
                    ICalendar cronCalendar    = new CronCalendar("0/5 * * * * ?");
                    ICalendar holidayCalendar = new HolidayCalendar();

                    // QRTZNET-86
                    ITrigger t = await scheduler.GetTrigger(new TriggerKey("NonExistingTrigger", "NonExistingGroup"));

                    Assert.IsNull(t);

                    AnnualCalendar cal = new AnnualCalendar();
                    await scheduler.AddCalendar("annualCalendar", cal, false, true);

                    IOperableTrigger calendarsTrigger = new SimpleTriggerImpl("calendarsTrigger", "test", 20, TimeSpan.FromMilliseconds(5));
                    calendarsTrigger.CalendarName = "annualCalendar";

                    JobDetailImpl jd = new JobDetailImpl("testJob", "test", typeof(NoOpJob));
                    await scheduler.ScheduleJob(jd, calendarsTrigger);

                    // QRTZNET-93
                    await scheduler.AddCalendar("annualCalendar", cal, true, true);

                    await scheduler.AddCalendar("baseCalendar", new BaseCalendar(), false, true);

                    await scheduler.AddCalendar("cronCalendar", cronCalendar, false, true);

                    await scheduler.AddCalendar("dailyCalendar", new DailyCalendar(DateTime.Now.Date, DateTime.Now.AddMinutes(1)), false, true);

                    await scheduler.AddCalendar("holidayCalendar", holidayCalendar, false, true);

                    await scheduler.AddCalendar("monthlyCalendar", new MonthlyCalendar(), false, true);

                    await scheduler.AddCalendar("weeklyCalendar", new WeeklyCalendar(), false, true);

                    await scheduler.AddCalendar("cronCalendar", cronCalendar, true, true);

                    await scheduler.AddCalendar("holidayCalendar", holidayCalendar, true, true);

                    Assert.IsNotNull(scheduler.GetCalendar("annualCalendar"));

                    JobDetailImpl lonelyJob = new JobDetailImpl("lonelyJob", "lonelyGroup", typeof(SimpleRecoveryJob));
                    lonelyJob.Durable          = true;
                    lonelyJob.RequestsRecovery = true;
                    await scheduler.AddJob(lonelyJob, false);

                    await scheduler.AddJob(lonelyJob, true);

                    string schedId = scheduler.SchedulerInstanceId;

                    int count = 1;

                    JobDetailImpl job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));

                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = true;
                    IOperableTrigger trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));
                    trigger.JobDataMap.Add("key", "value");
                    trigger.EndTimeUtc = DateTime.UtcNow.AddYears(10);

                    trigger.StartTimeUtc = DateTime.Now.AddMilliseconds(1000L);
                    await scheduler.ScheduleJob(job, trigger);

                    // check that trigger was stored
                    ITrigger persisted = await scheduler.GetTrigger(new TriggerKey("trig_" + count, schedId));

                    Assert.IsNotNull(persisted);
                    Assert.IsTrue(persisted is SimpleTriggerImpl);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(2000L));
                    await scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryStatefulJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(3));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    await scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(4));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    await scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                    await scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    IOperableTrigger ct = new CronTriggerImpl("cron_trig_" + count, schedId, "0/10 * * * * ?");
                    ct.JobDataMap.Add("key", "value");
                    ct.StartTimeUtc = DateTime.Now.AddMilliseconds(1000);

                    await scheduler.ScheduleJob(job, ct);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    DailyTimeIntervalTriggerImpl nt = new DailyTimeIntervalTriggerImpl("nth_trig_" + count, schedId, new TimeOfDay(1, 1, 1), new TimeOfDay(23, 30, 0), IntervalUnit.Hour, 1);
                    nt.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);

                    await scheduler.ScheduleJob(job, nt);

                    DailyTimeIntervalTriggerImpl nt2 = new DailyTimeIntervalTriggerImpl();
                    nt2.Key          = new TriggerKey("nth_trig2_" + count, schedId);
                    nt2.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);
                    nt2.JobKey       = job.Key;
                    await scheduler.ScheduleJob(nt2);

                    // GitHub issue #92
                    await scheduler.GetTrigger(nt2.Key);

                    // GitHub issue #98
                    nt2.StartTimeOfDay = new TimeOfDay(1, 2, 3);
                    nt2.EndTimeOfDay   = new TimeOfDay(2, 3, 4);

                    await scheduler.UnscheduleJob(nt2.Key);

                    await scheduler.ScheduleJob(nt2);

                    var triggerFromDb = (IDailyTimeIntervalTrigger)await scheduler.GetTrigger(nt2.Key);

                    Assert.That(triggerFromDb.StartTimeOfDay.Hour, Is.EqualTo(1));
                    Assert.That(triggerFromDb.StartTimeOfDay.Minute, Is.EqualTo(2));
                    Assert.That(triggerFromDb.StartTimeOfDay.Second, Is.EqualTo(3));

                    Assert.That(triggerFromDb.EndTimeOfDay.Hour, Is.EqualTo(2));
                    Assert.That(triggerFromDb.EndTimeOfDay.Minute, Is.EqualTo(3));
                    Assert.That(triggerFromDb.EndTimeOfDay.Second, Is.EqualTo(4));

                    job.RequestsRecovery = (true);
                    CalendarIntervalTriggerImpl intervalTrigger = new CalendarIntervalTriggerImpl(
                        "calint_trig_" + count,
                        schedId,
                        DateTime.UtcNow.AddMilliseconds(300),
                        DateTime.UtcNow.AddMinutes(1),
                        IntervalUnit.Second,
                        8);
                    intervalTrigger.JobKey = job.Key;

                    await scheduler.ScheduleJob(intervalTrigger);

                    // bulk operations
                    var        info     = new Dictionary <IJobDetail, ISet <ITrigger> >();
                    IJobDetail detail   = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    ITrigger   simple   = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                    var        triggers = new HashSet <ITrigger>();
                    triggers.Add(simple);
                    info[detail] = triggers;

                    await scheduler.ScheduleJobs(info, true);

                    Assert.IsTrue(await scheduler.CheckExists(detail.Key));
                    Assert.IsTrue(await scheduler.CheckExists(simple.Key));

                    // QRTZNET-243
                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupContains("a").DeepClone());

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("a").DeepClone());

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("a").DeepClone());

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("a").DeepClone());

                    await scheduler.Start();

                    await Task.Delay(TimeSpan.FromSeconds(3));

                    await scheduler.PauseAll();

                    await scheduler.ResumeAll();

                    await scheduler.PauseJob(new JobKey("job_1", schedId));

                    await scheduler.ResumeJob(new JobKey("job_1", schedId));

                    await scheduler.PauseJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

                    await Task.Delay(TimeSpan.FromSeconds(1));

                    await scheduler.ResumeJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

                    await scheduler.PauseTrigger(new TriggerKey("trig_2", schedId));

                    await scheduler.ResumeTrigger(new TriggerKey("trig_2", schedId));

                    await scheduler.PauseTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    var pausedTriggerGroups = await scheduler.GetPausedTriggerGroups();

                    Assert.AreEqual(1, pausedTriggerGroups.Count);

                    await Task.Delay(TimeSpan.FromSeconds(3));

                    await scheduler.ResumeTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    Assert.IsNotNull(scheduler.GetTrigger(new TriggerKey("trig_2", schedId)));
                    Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_1", schedId)));
                    Assert.IsNotNull(scheduler.GetMetaData());
                    Assert.IsNotNull(scheduler.GetCalendar("weeklyCalendar"));

                    var genericjobKey = new JobKey("genericJob", "genericGroup");
                    GenericJobType.Reset();
                    var genericJob = JobBuilder.Create <GenericJobType>()
                                     .WithIdentity(genericjobKey)
                                     .StoreDurably()
                                     .Build();

                    await scheduler.AddJob(genericJob, false);

                    genericJob = await scheduler.GetJobDetail(genericjobKey);

                    Assert.That(genericJob, Is.Not.Null);
                    await scheduler.TriggerJob(genericjobKey);

                    GenericJobType.WaitForTrigger(TimeSpan.FromSeconds(20));

                    Assert.That(GenericJobType.TriggeredCount, Is.EqualTo(1));
                    await scheduler.Standby();

                    CollectionAssert.IsNotEmpty(await scheduler.GetCalendarNames());
                    CollectionAssert.IsNotEmpty(await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(schedId)));

                    CollectionAssert.IsNotEmpty(await scheduler.GetTriggersOfJob(new JobKey("job_2", schedId)));
                    Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_2", schedId)));

                    await scheduler.DeleteCalendar("cronCalendar");

                    await scheduler.DeleteCalendar("holidayCalendar");

                    await scheduler.DeleteJob(new JobKey("lonelyJob", "lonelyGroup"));

                    await scheduler.DeleteJob(job.Key);

                    await scheduler.GetJobGroupNames();

                    await scheduler.GetCalendarNames();

                    await scheduler.GetTriggerGroupNames();

                    await TestMatchers(scheduler);
                }
            }
            finally
            {
                await scheduler.Shutdown(false);
            }
        }
Ejemplo n.º 4
0
        public Task Execute(IJobExecutionContext context)
        {
            return(Task.Run(async() =>
            {
                string f_Id = "", msg = "成功";
                int logStatus = 1;
                JobDataMap jobData = null;
                AutoJobEntity autoJobEntity = null;
                try
                {
                    jobData = context.JobDetail.JobDataMap;
                    f_Id = jobData["Id"].ToString();
                    // 获取数据库中的任务
                    autoJobEntity = autoJobApp.GetForm(f_Id);
                    if (autoJobEntity != null)
                    {
                        if (autoJobEntity.JobStatus == 1)
                        {
                            CronTriggerImpl trigger = context.Trigger as CronTriggerImpl;
                            if (trigger != null)
                            {
                                if (trigger.CronExpressionString != autoJobEntity.CronExpression)
                                {
                                    // 更新任务周期
                                    trigger.CronExpressionString = autoJobEntity.CronExpression;
                                    await JobScheduler.GetScheduler().RescheduleJob(trigger.Key, trigger);
                                }

                                #region 执行任务
                                switch (context.JobDetail.Key.Name)
                                {
                                case "Comrms":    //期货
                                    if (!new GetComrmsJob().Start())
                                    {
                                        logStatus = 0;
                                        msg = "失败";
                                    }
                                    break;

                                default:
                                    //todo
                                    break;
                                }
                                #endregion
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    msg = ex.ToString();
                    logStatus = 0;
                }

                try
                {
                    if (autoJobEntity != null)
                    {
                        if (autoJobEntity.JobStatus == 1)
                        {
                            //更新下次运行时间
                            DbHelper.ExecuteNonQuery("update Sys_AutoJob set NextStartTime='" + context.NextFireTimeUtc.Value.DateTime.AddHours(8) + "' where F_Id='" + autoJobEntity.F_Id + "'");

                            //记录执行状态
                            FRow fRow = new FRow("Sys_AutoJobLog");
                            fRow["F_CreatorTime"] = context.JobDetail.Key.Group;
                            fRow["JobGroupName"] = context.JobDetail.Key.Name;
                            fRow["LogStatus"] = logStatus;
                            fRow["F_Description"] = msg;
                            fRow.Insert();
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogFactory.GetLogger().Error(ex);
                }
            }));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 创建CronTrigger,立刻执行
        /// trigger将定期按时执行,
        /// 意味着如果下一个周期到来,而上一次周期执行未完成,job仍然在一个新线程中执行
        ///
        /// Cron表达式由6个(或者7个)空格分隔的时间元素组成,按顺序依次是
        /// 元素               取值       特殊字符
        /// 秒                (0-59)      ,-*/
        /// 分钟              (0-59)      ,-*/
        /// 小时              (0-23)      ,-*/
        /// day of Month      (1-31)     ,-*?/LW   需要考虑月实际的天数
        /// 月                (1-12)      ,-*/
        /// day of week       (1-7)       ,-*?/L#   1表示星期天 7表示星期六
        /// 年  可选     empty,1970-2099  ,-*/
        ///
        ///
        /// *   表示选择所有可能的值,“*”在子表达式(秒)里表示每秒的含义
        /// ?   字符可以用在day-of-month及day-of-week域中,它用来表示“没有指定值”。这对于需要指定一个或者两个域的值而不需要对其他域进行设置来说相当有用。
        /// -   指定范围,如在小时域中,  10-12表示10,11,12点
        /// ,   指定额外的值,如在小时域中,  10,12,12表示10,12,13点
        /// /   指定增量,   在分钟域中,  5/15表示从5分钟开始每隔15分钟执行,即5 20,35,50分钟执行
        ///
        ///
        ///
        /// 0 0 12 * * ?    表示每天12点执行
        /// 0/5 * * * * ?   表示每5秒执行一次
        /// 0 0/5 * * * ?   表示每5分钟执行一次
        /// 0 0 4 5 * ?     每月5日 4 点执行
        /// 0 17 4 ? * 1,3,5     每个星期天 星期二 星期四 4点 17分执行
        /// </summary>
        /// <param name="triggerName">triggerName,必须唯一</param>
        /// <param name="cronExpression"></param>
        /// <returns></returns>
        public static ITrigger CreateCronTrigger(String triggerName, String cronExpression)
        {
            ITrigger trigger = new CronTriggerImpl(triggerName, null, cronExpression);

            return(trigger);
        }
Ejemplo n.º 6
0
        public void ManagedTask(TaskSettings settings)
        {
            foreach (var setting in settings)
            {
                _sched.DeleteJob(new JobKey(setting.JobType, TaskGroup));

                if (setting.Enabled)
                {
                    if (string.IsNullOrEmpty(setting.JobType))
                    {
                        continue;
                    }

                    var taskType = Type.GetType(setting.JobType);
                    if (taskType == null)
                    {
                        continue;
                    }
                    if (_sched.CheckExists(new JobKey(setting.JobType, TaskGroup)))
                    {
                        continue;
                    }

                    var jobDetail = new JobDetailImpl(setting.JobType, TaskGroup, taskType);
                    jobDetail.JobDataMap[DataMap] = setting;
                    var cronExpression = GetCronString(setting);
                    if (string.IsNullOrEmpty(cronExpression))
                    {
                        continue;
                    }

                    var trigger = new CronTriggerImpl(setting.JobType, TaskGroup, setting.JobType, TaskGroup, cronExpression);
                    _sched.ScheduleJob(jobDetail, trigger);
                }
            }

            var moduleTasks = AttachedModules.GetModules <IModuleTask>();

            foreach (var moduleTask in moduleTasks)
            {
                var classInstance = (IModuleTask)Activator.CreateInstance(moduleTask, null);
                var tasksSettings = classInstance.GetTasks();

                foreach (var setting in tasksSettings)
                {
                    _sched.DeleteJob(new JobKey(setting.JobType, ModuleGroup));

                    if (setting.Enabled)
                    {
                        var type = Type.GetType(setting.JobType);
                        if (type == null)
                        {
                            continue;
                        }

                        var cronExpression = GetCronString(setting);
                        if (string.IsNullOrEmpty(cronExpression))
                        {
                            continue;
                        }

                        var jobDetail = new JobDetailImpl(setting.JobType, ModuleGroup, type);
                        jobDetail.JobDataMap[DataMap] = setting;

                        var trigger = new CronTriggerImpl(setting.JobType, ModuleGroup, setting.JobType, ModuleGroup, cronExpression);
                        _sched.ScheduleJob(jobDetail, trigger);
                    }
                }
            }
        }
Ejemplo n.º 7
0
      private bool ExecuteWebApi(SchedulerConfigModel list)
      {
          try
          {
              var             flag      = true;
              SchedulerHelper scheduler = new SchedulerHelper();

              SchedulerRequest request = new SchedulerRequest();
              request.JobName          = list.JobName;
              request.JobGroup         = list.JobGroup;
              request.TriggerName      = list.JobName + "Trigger";
              request.TriggerGroupName = list.JobGroup + "Trigger";
              request.CronTab          = list.CronTab;
              request.StartTime        = list.StartTime;
              if (list.EndTime != null)
              {
                  request.EndTime = list.EndTime;
              }
              else
              {
                  request.EndTime = null;
              }
              request.RequestType = list.RequestType;
              request.RequestUrl  = list.RequestUrl;

              var json = JsonConvert.SerializeObject(request);

              DateTimeOffset?end = null;
              if (request.EndTime != null)
              {
                  end = DateTime.SpecifyKind(Convert.ToDateTime(request.EndTime), DateTimeKind.Local);
                  if (request.EndTime < DateTime.Now)
                  {
                      flag = false;
                  }
              }
              if (flag)
              {
                  IJobDetail jobDetail = JobBuilder.Create <FileJob>()
                                         .WithIdentity(request.JobName, request.JobGroup)
                                         .UsingJobData("jobJson", json)
                                         .Build();

                  CronTriggerImpl tigger = (CronTriggerImpl)TriggerBuilder.Create()
                                           .WithIdentity(request.TriggerName, request.TriggerGroupName)
                                           .WithCronSchedule(request.CronTab)
                                           .ForJob(request.JobName, request.JobGroup)
                                           .StartNow()
                                           .EndAt(end)
                                           .Build();

                  DateTimeOffset dt = scheduler.scheduleJob(jobDetail, tigger);
              }
              else
              {
              }

              return(true);
          }
          catch (Exception ex)
          {
              //插入日志
              SchedulerRequest request = new SchedulerRequest();
              request.JobGroup    = list.JobGroup;
              request.JobName     = list.JobName;
              request.RequestType = list.RequestType;
              request.RequestUrl  = list.RequestUrl;
              request.ReturnMsg   = "Job-Exception: " + (ex.ToString().Length > 450 ? ex.ToString().Substring(0, 450) : ex.ToString());
              request.LogStatus   = (int)JobEnum.LogStatus.ExceptInfo;
              SchedulerConfigDB.InsertLog(request);
              //数据状态更新为0,防止重复执行
              SchedulerConfigDB.UpdateStatus(list.ID);
              return(false);
          }
      }
Ejemplo n.º 8
0
        public void StressTest()
        {
            NameValueCollection properties = new NameValueCollection();

            properties["quartz.scheduler.instanceName"]      = "TestScheduler";
            properties["quartz.scheduler.instanceId"]        = "instance_one";
            properties["quartz.threadPool.type"]             = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"]      = "10";
            properties["quartz.threadPool.threadPriority"]   = "Normal";
            properties["quartz.jobStore.misfireThreshold"]   = "60000";
            properties["quartz.jobStore.type"]               = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
            properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz";
            properties["quartz.jobStore.useProperties"]      = "false";
            properties["quartz.jobStore.dataSource"]         = "default";
            properties["quartz.jobStore.tablePrefix"]        = "QRTZ_";
            properties["quartz.jobStore.clustered"]          = "false";
            properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";

            string connectionString = "Server=(local);Database=quartz;Trusted_Connection=True;";

            properties["quartz.dataSource.default.connectionString"] = connectionString;
            properties["quartz.dataSource.default.provider"]         = "SqlServer-20";

            // First we must get a reference to a scheduler
            ISchedulerFactory sf    = new StdSchedulerFactory(properties);
            IScheduler        sched = sf.GetScheduler();

            try
            {
                sched.Clear();

                JobDetailImpl lonelyJob = new JobDetailImpl("lonelyJob", "lonelyGroup", typeof(SimpleRecoveryJob));
                lonelyJob.Durable          = true;
                lonelyJob.RequestsRecovery = true;
                sched.AddJob(lonelyJob, false);
                sched.AddJob(lonelyJob, true);

                string schedId = sched.SchedulerInstanceId;

                JobDetailImpl job = new JobDetailImpl("job_to_use", schedId, typeof(SimpleRecoveryJob));

                for (int i = 0; i < 100000; ++i)
                {
                    IOperableTrigger trigger = new SimpleTriggerImpl("stressing_simple", SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromSeconds(1));
                    trigger.StartTimeUtc = DateTime.Now.AddMilliseconds(i);
                    sched.ScheduleJob(job, trigger);
                }

                for (int i = 0; i < 100000; ++i)
                {
                    IOperableTrigger ct = new CronTriggerImpl("stressing_cron", "0/1 * * * * ?");
                    ct.StartTimeUtc = DateTime.Now.AddMilliseconds(i);
                    sched.ScheduleJob(job, ct);
                }

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                sched.Start();
                Thread.Sleep(TimeSpan.FromMinutes(3));
                stopwatch.Stop();
                Console.WriteLine("Took: " + stopwatch.Elapsed);
            }
            finally
            {
                sched.Shutdown(false);
            }
        }
Ejemplo n.º 9
0
        private static void Start(Task task, AppDomain domain)
        {
            //throw new SchedulerException("SchedulerException");

            //在应用程序域中创建实例返回并保存在job中,这是最终调用任务执行的实例
            TaskBase instance = domain.CreateInstanceFromAndUnwrap(AssemblyHelper.GetTaskAssemblyPath(task.AssemblyName), task.ClassName) as TaskBase;

            if (instance == null)
            {
                throw new InvalidCastException($"任务实例创建失败,请确认目标任务是否派生自TaskBase类型。程序集:{task.AssemblyName},类型:{task.ClassName}");
            }
            // instance.logger = new LogWriter(); ;
            JobDataMap map = new JobDataMap
            {
                new KeyValuePair <string, object> ("domain", domain),
                new KeyValuePair <string, object> ("instance", instance),
                new KeyValuePair <string, object> ("name", task.Title),
                new KeyValuePair <string, object> ("params", task.CustomParamsJson)
            };
            string     jobName = task.Id.ToString().ToLower();
            IJobDetail job     = JobBuilder.Create(typeof(RootJob)).WithIdentity(jobName)
                                 .SetJobData(map)
                                 //.UsingJobData("assembly", task.AssemblyName)
                                 //.UsingJobData("class", task.ClassName)
                                 .Build();

            //添加触发器
            _scheduler.ListenerManager.AddJobListener(new JobRunListener(jobName),
                                                      KeyMatcher <JobKey> .KeyEquals(new JobKey(jobName)));

            if (task.RunMoreTimes)
            {
                if (!CronExpression.IsValidExpression(task.CronExpression))
                {
                    throw new Exception("cron表达式验证失败");
                }
                CronTriggerImpl trigger = new CronTriggerImpl
                {
                    CronExpressionString = task.CronExpression,
                    Name        = task.Title,
                    Key         = new TriggerKey(task.Id.ToString()),
                    Description = task.Remark
                };
                if (task.StartDate.HasValue)
                {
                    trigger.StartTimeUtc = TimeZoneInfo.ConvertTimeToUtc(task.StartDate.Value);
                }
                if (task.EndDate.HasValue)
                {
                    trigger.EndTimeUtc = TimeZoneInfo.ConvertTimeToUtc(task.EndDate.Value);
                }

                _scheduler.ScheduleJob(job, trigger);
            }
            else
            {
                DateTimeOffset start = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now);
                if (task.StartDate.HasValue)
                {
                    start = TimeZoneInfo.ConvertTimeToUtc(task.StartDate.Value);
                }
                DateTimeOffset end = start.AddMinutes(1);
                if (task.EndDate.HasValue)
                {
                    end = TimeZoneInfo.ConvertTimeToUtc(task.EndDate.Value);
                }
                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity(jobName)
                                   .StartAt(start)
                                   .WithSimpleSchedule(x => x
                                                       .WithRepeatCount(1).WithIntervalInMinutes(1))
                                   .EndAt(end)
                                   .Build();
                _scheduler.ScheduleJob(job, trigger);
            }

            LogHelper.Info($"任务\"{task.Title}\"启动成功!", task.Id);

            System.Threading.Tasks.Task.Run(() =>
            {
                while (true)
                {
                    var log = instance.ReadLog();
                    if (log != null)
                    {
                        //System.Diagnostics.Debug.WriteLine("queue:" + log.Contents);
                        LogManager.Queue.Write(log);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(3000);
                    }
                }
            });
        }
Ejemplo n.º 10
0
 public Task Execute(IJobExecutionContext context)
 {
     return(Task.Run(async() =>
     {
         string jobId = "";
         JobDataMap jobData = null;
         OpenJobEntity dbJobEntity = null;
         DateTime now = DateTime.Now;
         try
         {
             jobData = context.JobDetail.JobDataMap;
             jobId = jobData["F_Id"].ToString();
             using (IDbContext _context = DBContexHelper.Contex())
             {
                 OpenJobsService autoJobService = new OpenJobsService(_context, _schedulerFactory, _iocJobfactory);
                 // 获取数据库中的任务
                 dbJobEntity = await autoJobService.GetForm(jobId);
                 if (dbJobEntity != null)
                 {
                     if (dbJobEntity.F_EnabledMark == true)
                     {
                         CronTriggerImpl trigger = context.Trigger as CronTriggerImpl;
                         if (trigger != null)
                         {
                             if (trigger.CronExpressionString != dbJobEntity.F_CronExpress)
                             {
                                 // 更新任务周期
                                 trigger.CronExpressionString = dbJobEntity.F_CronExpress;
                                 await _scheduler.RescheduleJob(trigger.Key, trigger);
                                 return;
                             }
                             #region 执行任务
                             _context.Session.BeginTransaction();
                             //反射执行就行
                             var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
                             //反射取指定前后缀的dll
                             var referencedAssemblies = Directory.GetFiles(path, "HaotianCloud.*.dll").Select(Assembly.LoadFrom).ToArray();
                             var types = referencedAssemblies
                                         .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces()
                                                                             .Contains(typeof(IJobTask)))).ToArray();
                             string filename = dbJobEntity.F_FileName;
                             var implementType = types.Where(x => x.IsClass && x.FullName == filename).FirstOrDefault();
                             var obj = System.Activator.CreateInstance(implementType, _context);   // 创建实例(带参数)
                             MethodInfo method = implementType.GetMethod("Start", new Type[] { }); // 获取方法信息
                             object[] parameters = null;
                             var temp = (Task <AlwaysResult>)method.Invoke(obj, parameters);       // 调用方法,参数为空
                             #endregion
                             //需要同步,不然数据库连接会断开
                             _context.Update <OpenJobEntity>(t => t.F_Id == jobId, a => new OpenJobEntity
                             {
                                 F_LastRunTime = now
                             });
                             OpenJobLogEntity log = new OpenJobLogEntity();
                             log.F_Id = Utils.GuId();
                             log.F_JobId = jobId;
                             log.F_JobName = dbJobEntity.F_JobName;
                             log.F_CreatorTime = now;
                             if (temp.Result.state.ToString() == ResultType.success.ToString())
                             {
                                 log.F_EnabledMark = true;
                                 log.F_Description = "执行成功," + temp.Result.message.ToString();
                             }
                             else
                             {
                                 log.F_EnabledMark = false;
                                 log.F_Description = "执行失败," + temp.Result.message.ToString();
                             }
                             string HandleLogProvider = GlobalContext.SystemConfig.HandleLogProvider;
                             if (HandleLogProvider != Define.CACHEPROVIDER_REDIS)
                             {
                                 _context.Insert(log);
                             }
                             else
                             {
                                 await HandleLogHelper.HSetAsync(log.F_JobId, log.F_Id, log);
                             }
                             _context.Session.CommitTransaction();
                         }
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             LogHelper.WriteWithTime(ex);
         }
     }));
 }
Ejemplo n.º 11
0
 /// <summary>
 /// 修改Job
 /// </summary>
 public async Task UpdateJob(string job_name, string job_group, string job_cron)
 {
     var          key  = GetTriggerKey(job_name, job_group);
     ICronTrigger cron = new CronTriggerImpl(job_name, job_group, job_name, job_group, job_cron);
     await _scheduler.RescheduleJob(key, cron);
 }
        public void Test(IScheduler scheduler, bool clearJobs, bool scheduleJobs)
        {
            try
            {
                if (clearJobs)
                {
                    scheduler.Clear();
                }

                if (scheduleJobs)
                {
                    ICalendar cronCalendar    = new CronCalendar("0/5 * * * * ?");
                    ICalendar holidayCalendar = new HolidayCalendar();

                    // QRTZNET-86
                    ITrigger t = scheduler.GetTrigger(new TriggerKey("NonExistingTrigger", "NonExistingGroup"));
                    Assert.IsNull(t);

                    AnnualCalendar cal = new AnnualCalendar();
                    scheduler.AddCalendar("annualCalendar", cal, false, true);

                    IOperableTrigger calendarsTrigger = new SimpleTriggerImpl("calendarsTrigger", "test", 20, TimeSpan.FromMilliseconds(5));
                    calendarsTrigger.CalendarName = "annualCalendar";

                    JobDetailImpl jd = new JobDetailImpl("testJob", "test", typeof(NoOpJob));
                    scheduler.ScheduleJob(jd, calendarsTrigger);

                    // QRTZNET-93
                    scheduler.AddCalendar("annualCalendar", cal, true, true);

                    scheduler.AddCalendar("baseCalendar", new BaseCalendar(), false, true);
                    scheduler.AddCalendar("cronCalendar", cronCalendar, false, true);
                    scheduler.AddCalendar("dailyCalendar", new DailyCalendar(DateTime.Now.Date, DateTime.Now.AddMinutes(1)), false, true);
                    scheduler.AddCalendar("holidayCalendar", holidayCalendar, false, true);
                    scheduler.AddCalendar("monthlyCalendar", new MonthlyCalendar(), false, true);
                    scheduler.AddCalendar("weeklyCalendar", new WeeklyCalendar(), false, true);

                    scheduler.AddCalendar("cronCalendar", cronCalendar, true, true);
                    scheduler.AddCalendar("holidayCalendar", holidayCalendar, true, true);

                    Assert.IsNotNull(scheduler.GetCalendar("annualCalendar"));

                    JobDetailImpl lonelyJob = new JobDetailImpl("lonelyJob", "lonelyGroup", typeof(SimpleRecoveryJob));
                    lonelyJob.Durable          = true;
                    lonelyJob.RequestsRecovery = true;
                    scheduler.AddJob(lonelyJob, false);
                    scheduler.AddJob(lonelyJob, true);

                    string schedId = scheduler.SchedulerInstanceId;

                    int count = 1;

                    JobDetailImpl job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));

                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = true;
                    IOperableTrigger trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));
                    trigger.JobDataMap.Add("key", "value");
                    trigger.EndTimeUtc = DateTime.UtcNow.AddYears(10);

                    trigger.StartTimeUtc = DateTime.Now.AddMilliseconds(1000L);
                    scheduler.ScheduleJob(job, trigger);

                    // check that trigger was stored
                    ITrigger persisted = scheduler.GetTrigger(new TriggerKey("trig_" + count, schedId));
                    Assert.IsNotNull(persisted);
                    Assert.IsTrue(persisted is SimpleTriggerImpl);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(2000L));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryStatefulJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(3));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(4));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    IOperableTrigger ct = new CronTriggerImpl("cron_trig_" + count, schedId, "0/10 * * * * ?");
                    ct.JobDataMap.Add("key", "value");
                    ct.StartTimeUtc = DateTime.Now.AddMilliseconds(1000);

                    scheduler.ScheduleJob(job, ct);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);

                    var timeZone1 = TimeZoneUtil.FindTimeZoneById("Central European Standard Time");
                    var timeZone2 = TimeZoneUtil.FindTimeZoneById("Mountain Standard Time");

                    DailyTimeIntervalTriggerImpl nt = new DailyTimeIntervalTriggerImpl("nth_trig_" + count, schedId, new TimeOfDay(1, 1, 1), new TimeOfDay(23, 30, 0), IntervalUnit.Hour, 1);
                    nt.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);
                    nt.TimeZone     = timeZone1;

                    scheduler.ScheduleJob(job, nt);

                    var loadedNt = (IDailyTimeIntervalTrigger)scheduler.GetTrigger(nt.Key);
                    Assert.That(loadedNt.TimeZone.Id, Is.EqualTo(timeZone1.Id));

                    nt.TimeZone = timeZone2;
                    scheduler.RescheduleJob(nt.Key, nt);

                    loadedNt = (IDailyTimeIntervalTrigger)scheduler.GetTrigger(nt.Key);
                    Assert.That(loadedNt.TimeZone.Id, Is.EqualTo(timeZone2.Id));

                    DailyTimeIntervalTriggerImpl nt2 = new DailyTimeIntervalTriggerImpl();
                    nt2.Key          = new TriggerKey("nth_trig2_" + count, schedId);
                    nt2.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);
                    nt2.JobKey       = job.Key;
                    scheduler.ScheduleJob(nt2);

                    // GitHub issue #92
                    scheduler.GetTrigger(nt2.Key);

                    // GitHub issue #98
                    nt2.StartTimeOfDay = new TimeOfDay(1, 2, 3);
                    nt2.EndTimeOfDay   = new TimeOfDay(2, 3, 4);

                    scheduler.UnscheduleJob(nt2.Key);
                    scheduler.ScheduleJob(nt2);

                    var triggerFromDb = (IDailyTimeIntervalTrigger)scheduler.GetTrigger(nt2.Key);
                    Assert.That(triggerFromDb.StartTimeOfDay.Hour, Is.EqualTo(1));
                    Assert.That(triggerFromDb.StartTimeOfDay.Minute, Is.EqualTo(2));
                    Assert.That(triggerFromDb.StartTimeOfDay.Second, Is.EqualTo(3));

                    Assert.That(triggerFromDb.EndTimeOfDay.Hour, Is.EqualTo(2));
                    Assert.That(triggerFromDb.EndTimeOfDay.Minute, Is.EqualTo(3));
                    Assert.That(triggerFromDb.EndTimeOfDay.Second, Is.EqualTo(4));

                    job.RequestsRecovery = (true);
                    CalendarIntervalTriggerImpl intervalTrigger = new CalendarIntervalTriggerImpl(
                        "calint_trig_" + count,
                        schedId,
                        DateTime.UtcNow.AddMilliseconds(300),
                        DateTime.UtcNow.AddMinutes(1),
                        IntervalUnit.Second,
                        8);
                    intervalTrigger.JobKey = job.Key;

                    scheduler.ScheduleJob(intervalTrigger);

                    // custom time zone
                    const string CustomTimeZoneId = "Custom TimeZone";
                    var          webTimezone      = TimeZoneInfo.CreateCustomTimeZone(
                        CustomTimeZoneId,
                        TimeSpan.FromMinutes(22),
                        null,
                        null);

                    TimeZoneUtil.CustomResolver = id =>
                    {
                        if (id == CustomTimeZoneId)
                        {
                            return(webTimezone);
                        }
                        return(null);
                    };

                    var customTimeZoneTrigger = TriggerBuilder.Create()
                                                .WithIdentity("customTimeZoneTrigger")
                                                .WithCronSchedule("0/5 * * * * ?", x => x.InTimeZone(webTimezone))
                                                .StartNow()
                                                .ForJob(job)
                                                .Build();

                    scheduler.ScheduleJob(customTimeZoneTrigger);
                    var loadedCustomTimeZoneTrigger = (ICronTrigger)scheduler.GetTrigger(customTimeZoneTrigger.Key);
                    Assert.That(loadedCustomTimeZoneTrigger.TimeZone.BaseUtcOffset, Is.EqualTo(TimeSpan.FromMinutes(22)));

                    // bulk operations
                    var        info     = new Dictionary <IJobDetail, Collection.ISet <ITrigger> >();
                    IJobDetail detail   = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    ITrigger   simple   = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                    var        triggers = new Collection.HashSet <ITrigger>();
                    triggers.Add(simple);
                    info[detail] = triggers;

                    scheduler.ScheduleJobs(info, true);

                    Assert.IsTrue(scheduler.CheckExists(detail.Key));
                    Assert.IsTrue(scheduler.CheckExists(simple.Key));

                    // QRTZNET-243
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupContains("a").DeepClone());
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("a").DeepClone());
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("a").DeepClone());
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("a").DeepClone());

                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("a").DeepClone());
                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("a").DeepClone());
                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("a").DeepClone());
                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("a").DeepClone());

                    scheduler.Start();

                    Thread.Sleep(TimeSpan.FromSeconds(3));

                    scheduler.PauseAll();

                    scheduler.ResumeAll();

                    scheduler.PauseJob(new JobKey("job_1", schedId));

                    scheduler.ResumeJob(new JobKey("job_1", schedId));

                    scheduler.PauseJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

                    Thread.Sleep(TimeSpan.FromSeconds(1));

                    scheduler.ResumeJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

                    scheduler.PauseTrigger(new TriggerKey("trig_2", schedId));
                    scheduler.ResumeTrigger(new TriggerKey("trig_2", schedId));

                    scheduler.PauseTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    Assert.AreEqual(1, scheduler.GetPausedTriggerGroups().Count);

                    Thread.Sleep(TimeSpan.FromSeconds(3));
                    scheduler.ResumeTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    Assert.IsNotNull(scheduler.GetTrigger(new TriggerKey("trig_2", schedId)));
                    Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_1", schedId)));
                    Assert.IsNotNull(scheduler.GetMetaData());
                    Assert.IsNotNull(scheduler.GetCalendar("weeklyCalendar"));

                    var genericjobKey = new JobKey("genericJob", "genericGroup");
                    var genericJob    = JobBuilder.Create <GenericJobType <string> >()
                                        .WithIdentity(genericjobKey)
                                        .StoreDurably()
                                        .Build();

                    scheduler.AddJob(genericJob, false);

                    genericJob = scheduler.GetJobDetail(genericjobKey);
                    Assert.That(genericJob, Is.Not.Null);
                    scheduler.TriggerJob(genericjobKey);

                    Thread.Sleep(TimeSpan.FromSeconds(20));

                    Assert.That(GenericJobType <string> .TriggeredCount, Is.EqualTo(1));
                    scheduler.Standby();

                    CollectionAssert.IsNotEmpty(scheduler.GetCalendarNames());
                    CollectionAssert.IsNotEmpty(scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(schedId)));

                    CollectionAssert.IsNotEmpty(scheduler.GetTriggersOfJob(new JobKey("job_2", schedId)));
                    Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_2", schedId)));

                    scheduler.DeleteCalendar("cronCalendar");
                    scheduler.DeleteCalendar("holidayCalendar");
                    scheduler.DeleteJob(new JobKey("lonelyJob", "lonelyGroup"));
                    scheduler.DeleteJob(job.Key);

                    scheduler.GetJobGroupNames();
                    scheduler.GetCalendarNames();
                    scheduler.GetTriggerGroupNames();

                    TestMatchers(scheduler);
                }
            }
            finally
            {
                scheduler.Shutdown(false);
            }
        }
Ejemplo n.º 13
0
        public void CreateTrigger(string jobName, string jobGroup, string processName, string solutionName,
                                  string userName, string schedulerName)
        {
            var scheduler = AppScheduler.GetSchedulerOrDefault(schedulerName);

            AppScheduler.RemoveJob(jobName, jobGroup, scheduler);
            IJobDetail      job                = AppScheduler.CreateProcessJob(jobName, jobGroup, processName, solutionName, userName);
            AbstractTrigger trigger            = null;
            string          triggerName        = jobName + "Trigger";
            string          triggerGroup       = jobGroup;
            TimeSpan        dailyFrom          = _periodicity.CustomFrom.TimeOfDay;
            TimeSpan        dailyTill          = _periodicity.CustomTill.TimeOfDay;
            DateTime        schedulerStart     = _periodicity.SchedulerStart;
            TimeSpan        schedulerStartTime = schedulerStart.TimeOfDay;
            DateTime?       schedulerFinish    = null;
            bool            isSchedulerEndless = _periodicity.IsSchedulerEndless;

            if (!isSchedulerEndless)
            {
                schedulerFinish = _periodicity.SchedulerFinish;
            }
            _periodicity.IsDaily = true;             // (Temporary for beta-version)
            bool isOncePerDay      = _periodicity.IsOnce;
            bool isManyTimesPerDay = _periodicity.IsCustom;

            const string cronAll        = "*";
            const string cronLast       = "L";
            const string cronNoSpecific = "?";

            TimeSpan syncTime       = _periodicity.OnceAt.TimeOfDay;
            TimeSpan repeatInterval = TimeSpan.Zero;

            if (isOncePerDay)
            {
                if (schedulerStartTime > syncTime)
                {
                    DateTime schedulerStartNextDay = schedulerStart.AddDays(1);
                    schedulerStart = new DateTime(schedulerStartNextDay.Year, schedulerStartNextDay.Month, schedulerStartNextDay.Day,
                                                  syncTime.Hours, syncTime.Minutes, syncTime.Seconds);
                }
            }
            else if (isManyTimesPerDay)
            {
                if (schedulerStartTime > dailyFrom)
                {
                    DateTime schedulerStartNextDay = schedulerStart.AddDays(1);
                    schedulerStart = new DateTime(schedulerStartNextDay.Year, schedulerStartNextDay.Month, schedulerStartNextDay.Day,
                                                  dailyFrom.Hours, dailyFrom.Minutes, dailyFrom.Seconds);
                }

                var customPeriodType = (HoursOrMinutes)_periodicity.CustomPeriodType;
                int periodCount      = _periodicity.CustomPeriod;
                if (customPeriodType == HoursOrMinutes.Hours)
                {
                    repeatInterval = new TimeSpan(0, periodCount, 0, 0);
                }
                else if (customPeriodType == HoursOrMinutes.Minutes)
                {
                    repeatInterval = new TimeSpan(0, 0, periodCount, 0);
                }
                else
                {
                    throw new ArgumentException("Custom interval type is invalid");
                }
            }

            int           repeatToEndOfDateInterval = int.MaxValue;
            DailyCalendar dailyCalendar             = null;
            const string  calendarName = "FromTillPeriodicityDailyCalendar";

            if (isManyTimesPerDay)
            {
                bool calendarAlreadyExists = false;
                foreach (var name in scheduler.GetCalendarNames())
                {
                    if (name == calendarName)
                    {
                        calendarAlreadyExists = true;
                        break;
                    }
                }
                if (!calendarAlreadyExists)
                {
                    //dailyCalendar = new DailyCalendar(dailyFrom.ToString("c"), dailyTill.ToString("c"));
                    dailyCalendar          = new DailyCalendar(_periodicity.CustomFrom.TimeOfDay.ToString("c"), _periodicity.CustomTill.TimeOfDay.ToString("c"));
                    dailyCalendar.TimeZone = _userConnection.CurrentUser.TimeZone;
                    scheduler.AddCalendar(calendarName, dailyCalendar, false, false);
                }
            }

            if (_periodicity.IsDaily)
            {
                int daysCount = 1;                 // Temporary for beta-version. Must be: //int daysCount = _periodicity.DailyPeriod;
                if (isOncePerDay)
                {
                    trigger = new SimpleTriggerImpl(triggerName, triggerGroup,
                                                    schedulerStart, schedulerFinish, repeatToEndOfDateInterval, new TimeSpan(daysCount, 0, 0, 0));
                }
                else if (isManyTimesPerDay)
                {
                    if (daysCount == 1)
                    {
                        trigger = new SimpleTriggerImpl(triggerName, triggerGroup,
                                                        schedulerStart, schedulerFinish, repeatToEndOfDateInterval, repeatInterval);
                        trigger.CalendarName = calendarName;
                    }
                    else
                    {
                        var      multiTrigger = new List <SimpleTriggerImpl>();
                        DateTime currDate     = schedulerStart;
                        DateTime stopDate     = isSchedulerEndless ? currDate.AddYears(5) : schedulerFinish.Value;
                        while (currDate <= stopDate)
                        {
                            var currDateEnd = new DateTime(currDate.Year, currDate.Month, currDate.Day,
                                                           dailyTill.Hours, dailyTill.Minutes, dailyTill.Seconds);
                            if (currDateEnd > stopDate)
                            {
                                currDateEnd = stopDate;
                            }
                            var multiTriggerPart = new SimpleTriggerImpl(triggerName, triggerGroup,
                                                                         currDate, currDateEnd, repeatToEndOfDateInterval, repeatInterval);
                            multiTriggerPart.CalendarName = calendarName;
                            multiTrigger.Add(multiTriggerPart);
                            if (currDate == schedulerStart)                               // is first?
                            // Set TimeSpan from dailyFrom:
                            {
                                currDate = new DateTime(currDate.Year, currDate.Month, currDate.Day,
                                                        dailyFrom.Hours, dailyFrom.Minutes, dailyFrom.Seconds);
                            }
                            currDate.AddDays(daysCount);
                        }
                        foreach (var multiTriggerPart in multiTrigger)
                        {
                            multiTriggerPart.MisfireInstruction = MisfireInstruction.SimpleTrigger.FireNow;
                            scheduler.ScheduleJob(job, trigger);
                        }
                    }
                }
            }
            else if (_periodicity.IsWeekly)
            {
                if (isOncePerDay)
                {
                    string cronDayOfWeek  = (_periodicity.DayOfWeek + 1).ToString();
                    string cronExpression = GetCronExpression(syncTime, cronNoSpecific, cronAll, cronDayOfWeek);
                    trigger = new CronTriggerImpl(triggerName, triggerGroup, jobName, jobGroup,
                                                  schedulerStart, schedulerFinish, cronExpression);
                }
                else if (isManyTimesPerDay)
                {
                    // multitrigger???
                }
            }
            else if (_periodicity.IsMonthly)
            {
                if (_periodicity.IsMonthlyCustom)
                {
                    if (isOncePerDay)
                    {
                        string cronExpression = GetCronExpression(syncTime, _periodicity.DayOfMonth.ToString(), cronAll, cronNoSpecific);
                        trigger = new CronTriggerImpl(triggerName, triggerGroup, jobName, jobGroup,
                                                      schedulerStart, schedulerFinish, cronExpression);
                    }
                    else if (isManyTimesPerDay)
                    {
                        // multitrigger???
                    }
                }
                else if (_periodicity.IsMonthlyLastDay)
                {
                    if (isOncePerDay)
                    {
                        string cronExpression = GetCronExpression(syncTime, cronLast, cronAll, cronNoSpecific);
                        trigger = new CronTriggerImpl(triggerName, triggerGroup, jobName, jobGroup,
                                                      schedulerStart, schedulerFinish, cronExpression);
                    }
                    else if (isManyTimesPerDay)
                    {
                        // multitrigger???
                    }
                }
            }

            if (trigger != null)
            {
                trigger.MisfireInstruction = MisfireInstruction.SimpleTrigger.FireNow;                 // TODO: SimpleTrigger????
                scheduler.ScheduleJob(job, trigger);
            }
        }
Ejemplo n.º 14
0
        public async Task TestSchedulerFactoryObjectWithPlainQuartzObjects()
        {
            IJobFactory jobFactory = new AdaptableJobFactory();

            TestObject    tb         = new TestObject("tb", 99);
            JobDetailImpl jobDetail0 = new JobDetailImpl();

            jobDetail0.JobType = typeof(IJob);
            jobDetail0.Name    = "myJob0";
            jobDetail0.Group   = SchedulerConstants.DefaultGroup;
            jobDetail0.JobDataMap.Add("testObject", tb);
            Assert.AreEqual(tb, jobDetail0.JobDataMap.Get("testObject"));

            CronTriggerImpl trigger0 = new CronTriggerImpl();

            trigger0.Name                 = "myTrigger0";
            trigger0.Group                = SchedulerConstants.DefaultGroup;
            trigger0.JobName              = "myJob0";
            trigger0.JobGroup             = SchedulerConstants.DefaultGroup;
            trigger0.StartTimeUtc         = DateTime.UtcNow;
            trigger0.CronExpressionString = "0/1 * * * * ?";

            TestMethodInvokingTask task1 = new TestMethodInvokingTask();
            MethodInvokingJobDetailFactoryObject mijdfb = new MethodInvokingJobDetailFactoryObject();

            mijdfb.Name         = "myJob1";
            mijdfb.Group        = SchedulerConstants.DefaultGroup;
            mijdfb.TargetObject = task1;
            mijdfb.TargetMethod = "doSomething";
            mijdfb.AfterPropertiesSet();
            IJobDetail jobDetail1 = (IJobDetail)mijdfb.GetObject();

            SimpleTriggerImpl trigger1 = new SimpleTriggerImpl();

            trigger1.Name           = "myTrigger1";
            trigger1.Group          = SchedulerConstants.DefaultGroup;
            trigger1.JobName        = "myJob1";
            trigger1.JobGroup       = SchedulerConstants.DefaultGroup;
            trigger1.StartTimeUtc   = DateTime.UtcNow;
            trigger1.RepeatCount    = SimpleTriggerImpl.RepeatIndefinitely;
            trigger1.RepeatInterval = TimeSpan.FromMilliseconds(20);

            IScheduler scheduler = A.Fake <IScheduler>();

            A.CallTo(() => scheduler.GetTrigger(A <TriggerKey> ._, A <CancellationToken> ._)).Returns(Task.FromResult <ITrigger>(null));
            A.CallTo(() => scheduler.GetJobDetail(A <JobKey> ._, A <CancellationToken> ._)).Returns(Task.FromResult <IJobDetail>(null));

            SchedulerFactoryObject schedulerFactoryObject = new TestSchedulerFactoryObject(scheduler);

            schedulerFactoryObject.JobFactory = jobFactory;
            schedulerFactoryObject.JobDetails = new IJobDetail[] { jobDetail0, jobDetail1 };
            schedulerFactoryObject.Triggers   = new ITrigger[] { trigger0, trigger1 };
            try
            {
                schedulerFactoryObject.AfterPropertiesSet();
                await schedulerFactoryObject.Start();
            }
            finally
            {
                schedulerFactoryObject.Dispose();
            }

            A.CallTo(scheduler)
            .Where(x => x.Method.Name.Equals("set_JobFactory"))
            .WhenArgumentsMatch(x => x.Get <IJobFactory>(0) == jobFactory)
            .MustHaveHappened();

            A.CallTo(() => scheduler.AddJob(jobDetail0, true, true, A <CancellationToken> ._)).MustHaveHappened();
            A.CallTo(() => scheduler.AddJob(jobDetail1, true, true, A <CancellationToken> ._)).MustHaveHappened();
            A.CallTo(() => scheduler.GetJobDetail(new JobKey("myJob0", SchedulerConstants.DefaultGroup), A <CancellationToken> ._)).MustHaveHappened();
            A.CallTo(() => scheduler.GetJobDetail(new JobKey("myJob1", SchedulerConstants.DefaultGroup), A <CancellationToken> ._)).MustHaveHappened();
            A.CallTo(() => scheduler.GetTrigger(new TriggerKey("myTrigger0", SchedulerConstants.DefaultGroup), A <CancellationToken> ._)).MustHaveHappened();
            A.CallTo(() => scheduler.GetTrigger(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup), A <CancellationToken> ._)).MustHaveHappened();
        }
Ejemplo n.º 15
0
        public void TestSchedulerFactoryObjectWithPlainQuartzObjects()
        {
            IJobFactory jobFactory = new AdaptableJobFactory();

            TestObject    tb         = new TestObject("tb", 99);
            JobDetailImpl jobDetail0 = new JobDetailImpl();

            jobDetail0.JobType = typeof(IJob);
            jobDetail0.Name    = ("myJob0");
            jobDetail0.Group   = (SchedulerConstants.DefaultGroup);
            jobDetail0.JobDataMap.Add("testObject", tb);
            Assert.AreEqual(tb, jobDetail0.JobDataMap.Get("testObject"));

            CronTriggerImpl trigger0 = new CronTriggerImpl();

            trigger0.Name                 = ("myTrigger0");
            trigger0.Group                = SchedulerConstants.DefaultGroup;
            trigger0.JobName              = "myJob0";
            trigger0.JobGroup             = SchedulerConstants.DefaultGroup;
            trigger0.StartTimeUtc         = (DateTime.UtcNow);
            trigger0.CronExpressionString = ("0/1 * * * * ?");

            TestMethodInvokingTask task1 = new TestMethodInvokingTask();
            MethodInvokingJobDetailFactoryObject mijdfb = new MethodInvokingJobDetailFactoryObject();

            mijdfb.Name         = ("myJob1");
            mijdfb.Group        = (SchedulerConstants.DefaultGroup);
            mijdfb.TargetObject = (task1);
            mijdfb.TargetMethod = ("doSomething");
            mijdfb.AfterPropertiesSet();
            IJobDetail jobDetail1 = (IJobDetail)mijdfb.GetObject();

            SimpleTriggerImpl trigger1 = new SimpleTriggerImpl();

            trigger1.Name           = "myTrigger1";
            trigger1.Group          = SchedulerConstants.DefaultGroup;
            trigger1.JobName        = "myJob1";
            trigger1.JobGroup       = SchedulerConstants.DefaultGroup;
            trigger1.StartTimeUtc   = (DateTime.UtcNow);
            trigger1.RepeatCount    = (SimpleTriggerImpl.RepeatIndefinitely);
            trigger1.RepeatInterval = TimeSpan.FromMilliseconds(20);

            IScheduler scheduler = MockRepository.GenerateMock <IScheduler>();

            SchedulerFactoryObject schedulerFactoryObject = new TestSchedulerFactoryObject(scheduler);

            schedulerFactoryObject.JobFactory = (jobFactory);
            schedulerFactoryObject.JobDetails = (new IJobDetail[] { jobDetail0, jobDetail1 });
            schedulerFactoryObject.Triggers   = (new ITrigger[] { trigger0, trigger1 });
            try
            {
                schedulerFactoryObject.AfterPropertiesSet();
                schedulerFactoryObject.Start();
            }
            finally
            {
                schedulerFactoryObject.Dispose();
            }

            scheduler.AssertWasCalled(x => x.JobFactory = jobFactory);
            scheduler.AssertWasCalled(x => x.AddJob(jobDetail0, true));
            scheduler.AssertWasCalled(x => x.AddJob(jobDetail1, true));
            scheduler.AssertWasCalled(x => x.GetJobDetail(new JobKey("myJob0", SchedulerConstants.DefaultGroup)));
            scheduler.AssertWasCalled(x => x.GetJobDetail(new JobKey("myJob1", SchedulerConstants.DefaultGroup)));
            scheduler.AssertWasCalled(x => x.GetTrigger(new TriggerKey("myTrigger0", SchedulerConstants.DefaultGroup)));
            scheduler.AssertWasCalled(x => x.GetTrigger(new TriggerKey("myTrigger1", SchedulerConstants.DefaultGroup)));
        }
Ejemplo n.º 16
0
        private void RunAdoJobStoreTest(string dbProvider, string connectionStringId,
                                        NameValueCollection extraProperties)
        {
            NameValueCollection properties = new NameValueCollection();

            properties["quartz.scheduler.instanceName"]      = "TestScheduler";
            properties["quartz.scheduler.instanceId"]        = "instance_one";
            properties["quartz.threadPool.type"]             = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"]      = "10";
            properties["quartz.threadPool.threadPriority"]   = "Normal";
            properties["quartz.jobStore.misfireThreshold"]   = "60000";
            properties["quartz.jobStore.type"]               = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
            properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz";
            properties["quartz.jobStore.useProperties"]      = "false";
            properties["quartz.jobStore.dataSource"]         = "default";
            properties["quartz.jobStore.tablePrefix"]        = "QRTZ_";
            properties["quartz.jobStore.clustered"]          = clustered.ToString();

            if (extraProperties != null)
            {
                foreach (string key in extraProperties.Keys)
                {
                    properties[key] = extraProperties[key];
                }
            }

            if (connectionStringId == "SQLServer" || connectionStringId == "SQLite")
            {
                // if running MS SQL Server we need this
                properties["quartz.jobStore.lockHandler.type"] =
                    "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz";
            }

            string connectionString;

            if (!dbConnectionStrings.TryGetValue(connectionStringId, out connectionString))
            {
                throw new Exception("Unknown connection string id: " + connectionStringId);
            }
            properties["quartz.dataSource.default.connectionString"] = connectionString;
            properties["quartz.dataSource.default.provider"]         = dbProvider;

            // First we must get a reference to a scheduler
            ISchedulerFactory sf    = new StdSchedulerFactory(properties);
            IScheduler        sched = sf.GetScheduler();

            try
            {
                if (clearJobs)
                {
                    CleanUp(sched);
                }

                if (scheduleJobs)
                {
                    ICalendar cronCalendar    = new CronCalendar("0/5 * * * * ?");
                    ICalendar holidayCalendar = new HolidayCalendar();

                    // QRTZNET-86
                    ITrigger t = sched.GetTrigger(new TriggerKey("NonExistingTrigger", "NonExistingGroup"));
                    Assert.IsNull(t);

                    AnnualCalendar cal = new AnnualCalendar();
                    sched.AddCalendar("annualCalendar", cal, false, true);

                    IOperableTrigger calendarsTrigger = new SimpleTriggerImpl("calendarsTrigger", "test", 20, TimeSpan.FromMilliseconds(5));
                    calendarsTrigger.CalendarName = "annualCalendar";

                    JobDetailImpl jd = new JobDetailImpl("testJob", "test", typeof(NoOpJob));
                    sched.ScheduleJob(jd, calendarsTrigger);

                    // QRTZNET-93
                    sched.AddCalendar("annualCalendar", cal, true, true);

                    sched.AddCalendar("baseCalendar", new BaseCalendar(), false, true);
                    sched.AddCalendar("cronCalendar", cronCalendar, false, true);
                    sched.AddCalendar("dailyCalendar", new DailyCalendar(DateTime.Now.Date, DateTime.Now.AddMinutes(1)), false, true);
                    sched.AddCalendar("holidayCalendar", holidayCalendar, false, true);
                    sched.AddCalendar("monthlyCalendar", new MonthlyCalendar(), false, true);
                    sched.AddCalendar("weeklyCalendar", new WeeklyCalendar(), false, true);

                    sched.AddCalendar("cronCalendar", cronCalendar, true, true);
                    sched.AddCalendar("holidayCalendar", holidayCalendar, true, true);

                    Assert.IsNotNull(sched.GetCalendar("annualCalendar"));

                    JobDetailImpl lonelyJob = new JobDetailImpl("lonelyJob", "lonelyGroup", typeof(SimpleRecoveryJob));
                    lonelyJob.Durable          = true;
                    lonelyJob.RequestsRecovery = true;
                    sched.AddJob(lonelyJob, false);
                    sched.AddJob(lonelyJob, true);

                    string schedId = sched.SchedulerInstanceId;

                    int count = 1;

                    JobDetailImpl job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));

                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = true;
                    IOperableTrigger trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));

                    trigger.StartTimeUtc = DateTime.Now.AddMilliseconds(1000L);
                    sched.ScheduleJob(job, trigger);

                    // check that trigger was stored
                    ITrigger persisted = sched.GetTrigger(new TriggerKey("trig_" + count, schedId));
                    Assert.IsNotNull(persisted);
                    Assert.IsTrue(persisted is SimpleTriggerImpl);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(2000L));
                    sched.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryStatefulJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(3));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    sched.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(4));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    sched.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                    sched.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    IOperableTrigger ct = new CronTriggerImpl("cron_trig_" + count, schedId, "0/10 * * * * ?");
                    ct.StartTimeUtc = DateTime.Now.AddMilliseconds(1000);

                    sched.ScheduleJob(job, ct);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    NthIncludedDayTrigger nt = new NthIncludedDayTrigger("cron_trig_" + count, schedId);
                    nt.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);
                    nt.N            = 1;

                    sched.ScheduleJob(job, nt);

                    sched.Start();

                    sched.PauseAll();

                    sched.ResumeAll();

                    sched.PauseJob(new JobKey("job_1", schedId));

                    sched.ResumeJob(new JobKey("job_1", schedId));

                    sched.PauseJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

                    Thread.Sleep(1000);

                    sched.ResumeJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

                    sched.PauseTrigger(new TriggerKey("trig_2", schedId));
                    sched.ResumeTrigger(new TriggerKey("trig_2", schedId));

                    sched.PauseTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    Assert.AreEqual(1, sched.GetPausedTriggerGroups().Count);

                    Thread.Sleep(1000);
                    sched.ResumeTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));


                    Thread.Sleep(TimeSpan.FromSeconds(20));

                    sched.Standby();

                    CollectionAssert.IsNotEmpty(sched.GetCalendarNames());
                    CollectionAssert.IsNotEmpty(sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(schedId)));

                    CollectionAssert.IsNotEmpty(sched.GetTriggersOfJob(new JobKey("job_2", schedId)));
                    Assert.IsNotNull(sched.GetJobDetail(new JobKey("job_2", schedId)));

                    sched.DeleteCalendar("cronCalendar");
                    sched.DeleteCalendar("holidayCalendar");
                    sched.DeleteJob(new JobKey("lonelyJob", "lonelyGroup"));
                }
            }
            finally
            {
                sched.Shutdown(false);
            }
        }
Ejemplo n.º 17
0
        public void Test(IScheduler scheduler, bool clearJobs, bool scheduleJobs)
        {
            try
            {
                if (clearJobs)
                {
                    scheduler.Clear();
                }

                if (scheduleJobs)
                {
                    ICalendar cronCalendar    = new CronCalendar("0/5 * * * * ?");
                    ICalendar holidayCalendar = new HolidayCalendar();

                    // QRTZNET-86
                    ITrigger t = scheduler.GetTrigger(new TriggerKey("NonExistingTrigger", "NonExistingGroup"));
                    Assert.IsNull(t);

                    AnnualCalendar cal = new AnnualCalendar();
                    scheduler.AddCalendar("annualCalendar", cal, false, true);

                    IOperableTrigger calendarsTrigger = new SimpleTriggerImpl("calendarsTrigger", "test", 20, TimeSpan.FromMilliseconds(5));
                    calendarsTrigger.CalendarName = "annualCalendar";

                    JobDetailImpl jd = new JobDetailImpl("testJob", "test", typeof(NoOpJob));
                    scheduler.ScheduleJob(jd, calendarsTrigger);

                    // QRTZNET-93
                    scheduler.AddCalendar("annualCalendar", cal, true, true);

                    scheduler.AddCalendar("baseCalendar", new BaseCalendar(), false, true);
                    scheduler.AddCalendar("cronCalendar", cronCalendar, false, true);
                    scheduler.AddCalendar("dailyCalendar", new DailyCalendar(DateTime.Now.Date, DateTime.Now.AddMinutes(1)), false, true);
                    scheduler.AddCalendar("holidayCalendar", holidayCalendar, false, true);
                    scheduler.AddCalendar("monthlyCalendar", new MonthlyCalendar(), false, true);
                    scheduler.AddCalendar("weeklyCalendar", new WeeklyCalendar(), false, true);

                    scheduler.AddCalendar("cronCalendar", cronCalendar, true, true);
                    scheduler.AddCalendar("holidayCalendar", holidayCalendar, true, true);

                    Assert.IsNotNull(scheduler.GetCalendar("annualCalendar"));

                    JobDetailImpl lonelyJob = new JobDetailImpl("lonelyJob", "lonelyGroup", typeof(SimpleRecoveryJob));
                    lonelyJob.Durable          = true;
                    lonelyJob.RequestsRecovery = true;
                    scheduler.AddJob(lonelyJob, false);
                    scheduler.AddJob(lonelyJob, true);

                    string schedId = scheduler.SchedulerInstanceId;

                    int count = 1;

                    JobDetailImpl job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));

                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = true;
                    IOperableTrigger trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));
                    trigger.JobDataMap.Add("key", "value");
                    trigger.EndTimeUtc = DateTime.UtcNow.AddYears(10);

                    trigger.StartTimeUtc = DateTime.Now.AddMilliseconds(1000L);
                    scheduler.ScheduleJob(job, trigger);

                    // check that trigger was stored
                    ITrigger persisted = scheduler.GetTrigger(new TriggerKey("trig_" + count, schedId));
                    Assert.IsNotNull(persisted);
                    Assert.IsTrue(persisted is SimpleTriggerImpl);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(2000L));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryStatefulJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(3));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(4));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                    scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    IOperableTrigger ct = new CronTriggerImpl("cron_trig_" + count, schedId, "0/10 * * * * ?");
                    ct.JobDataMap.Add("key", "value");
                    ct.StartTimeUtc = DateTime.Now.AddMilliseconds(1000);

                    scheduler.ScheduleJob(job, ct);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    NthIncludedDayTrigger nt = new NthIncludedDayTrigger("nth_trig_" + count, schedId);
                    nt.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);
                    nt.N            = 1;

                    scheduler.ScheduleJob(job, nt);

                    job.RequestsRecovery = (true);
                    CalendarIntervalTriggerImpl intervalTrigger = new CalendarIntervalTriggerImpl(
                        "calint_trig_" + count,
                        schedId,
                        DateTime.UtcNow.AddMilliseconds(300),
                        DateTime.UtcNow.AddMinutes(1),
                        IntervalUnit.Second,
                        8);
                    intervalTrigger.JobKey = job.Key;

                    scheduler.ScheduleJob(intervalTrigger);

                    // bulk operations
                    IDictionary <IJobDetail, IList <ITrigger> > info = new Dictionary <IJobDetail, IList <ITrigger> >();
                    IJobDetail      detail   = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    ITrigger        simple   = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                    List <ITrigger> triggers = new List <ITrigger>();
                    triggers.Add(simple);
                    info[detail] = triggers;

                    scheduler.ScheduleJobs(info, true);

                    Assert.IsTrue(scheduler.CheckExists(detail.Key));
                    Assert.IsTrue(scheduler.CheckExists(simple.Key));

                    // QRTZNET-243
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupContains("a").DeepClone());
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("a").DeepClone());
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("a").DeepClone());
                    scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("a").DeepClone());

                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("a").DeepClone());
                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("a").DeepClone());
                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("a").DeepClone());
                    scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("a").DeepClone());

                    scheduler.Start();

                    Thread.Sleep(TimeSpan.FromSeconds(3));

                    scheduler.PauseAll();

                    scheduler.ResumeAll();

                    scheduler.PauseJob(new JobKey("job_1", schedId));

                    scheduler.ResumeJob(new JobKey("job_1", schedId));

                    scheduler.PauseJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

                    Thread.Sleep(TimeSpan.FromSeconds(1));

                    scheduler.ResumeJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

                    scheduler.PauseTrigger(new TriggerKey("trig_2", schedId));
                    scheduler.ResumeTrigger(new TriggerKey("trig_2", schedId));

                    scheduler.PauseTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    Assert.AreEqual(1, scheduler.GetPausedTriggerGroups().Count);

                    Thread.Sleep(TimeSpan.FromSeconds(3));
                    scheduler.ResumeTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    Assert.IsNotNull(scheduler.GetTrigger(new TriggerKey("trig_2", schedId)));
                    Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_1", schedId)));
                    Assert.IsNotNull(scheduler.GetMetaData());
                    Assert.IsNotNull(scheduler.GetCalendar("weeklyCalendar"));

                    Thread.Sleep(TimeSpan.FromSeconds(20));

                    scheduler.Standby();

                    CollectionAssert.IsNotEmpty(scheduler.GetCalendarNames());
                    CollectionAssert.IsNotEmpty(scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(schedId)));

                    CollectionAssert.IsNotEmpty(scheduler.GetTriggersOfJob(new JobKey("job_2", schedId)));
                    Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_2", schedId)));

                    scheduler.DeleteCalendar("cronCalendar");
                    scheduler.DeleteCalendar("holidayCalendar");
                    scheduler.DeleteJob(new JobKey("lonelyJob", "lonelyGroup"));
                    scheduler.DeleteJob(job.Key);

                    scheduler.GetJobGroupNames();
                    scheduler.GetCalendarNames();
                    scheduler.GetTriggerGroupNames();
                }
            }
            finally
            {
                scheduler.Shutdown(false);
            }
        }
        public void CronTrigger_AfterTriggerUpdate_Retains_Cron_Type()
        {
            //Arrange
            var cronTriggerImpl = new CronTriggerImpl("Trigger", "Trigger.Group", "JobName", "JobGroup", "0 15 23 * * ?");

            cronTriggerImpl.CalendarName       = "calName";
            cronTriggerImpl.MisfireInstruction = 1;
            cronTriggerImpl.Description        = "Description";
            cronTriggerImpl.SetPreviousFireTimeUtc(new DateTimeOffset(new DateTime(2010, 1, 1)));
            cronTriggerImpl.SetNextFireTimeUtc(new DateTimeOffset(new DateTime(2010, 2, 1)));
            cronTriggerImpl.JobKey   = new JobKey("JobKey", "JobKeyGroup");
            cronTriggerImpl.Priority = 1;

            var dbProvider = MockRepository.GenerateStub <IDbProvider>();
            var dbCommand  = MockRepository.GenerateStub <IDbCommand>();
            var dataParameterCollection = MockRepository.GenerateStub <IDataParameterCollection>();

            dbProvider.Stub(d => d.CreateCommand()).Return(dbCommand).Repeat.Any();
            Func <StubDataParameter> dataParam = () => new StubDataParameter();

            dbProvider.Stub(d => d.CreateParameter()).Do(dataParam);
            dbCommand.Stub(c => c.CreateParameter()).Do(dataParam);

            var dataParameterCollectionOutputs = new List <object>();

            Func <object, int> dataParameterFunc = x =>
            {
                dataParameterCollectionOutputs.Add(x);
                return(1);
            };

            dataParameterCollection.Stub(d => d.Add(Arg <object> .Is.Anything)).Do(dataParameterFunc);

            dbCommand.Stub(c => c.Parameters).Return(dataParameterCollection);
            var metaData = MockRepository.GenerateStub <DbMetadata>();

            dbProvider.Stub(d => d.Metadata).Return(metaData);

            Func <string, string> paramFunc = x => x;

            metaData.Stub(m => m.GetParameterName(Arg <string> .Is.Anything)).Do(paramFunc);

            DelegateInitializationArgs args = new DelegateInitializationArgs();

            args.Logger         = LogManager.GetLogger(GetType());
            args.TablePrefix    = "QRTZ_";
            args.InstanceName   = "TESTSCHED";
            args.InstanceId     = "INSTANCE";
            args.DbProvider     = dbProvider;
            args.TypeLoadHelper = new SimpleTypeLoadHelper();

            var adoDelegate = new StdAdoDelegate();

            adoDelegate.Initialize(args);

            var dbConnection = new StubConnection();
            var conn         = new ConnectionAndTransactionHolder(dbConnection, null);
            var jobDetail    = MockRepository.GenerateMock <IJobDetail>();
            var jobDataMap   = new JobDataMap();

            jobDataMap.ClearDirtyFlag();
            cronTriggerImpl.JobDataMap = jobDataMap;

            //Act
            adoDelegate.UpdateTrigger(conn, cronTriggerImpl, "state", jobDetail);

            //Assert
            var resultDataParameters = dataParameterCollectionOutputs.Select(x => x as IDataParameter).Where(x => x.ParameterName == "triggerType").FirstOrDefault();

            Assert.AreEqual("CRON", resultDataParameters.Value);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 把新加的Job添加到调度器
        /// </summary>
        /// <param name="scheduler">调度器</param>
        /// <param name="jobInfo">Job信息</param>
        private static async void ManagerJob(IScheduler scheduler, JobInfoEntity jobInfo)
        {
            if (CronExpression.IsValidExpression(jobInfo.CronExpression))
            {
                Type type = GetClassInfo(jobInfo.AssemblyName, jobInfo.ClassName);
                if (type != null)
                {
                    try
                    {
                        IJobDetail job = new JobDetailImpl(jobInfo.Id.ToString(), jobInfo.Id.ToString() + "Group", type);
                        job.JobDataMap.Add("Parameters", jobInfo.JobArgs);
                        job.JobDataMap.Add("JobName", jobInfo.Name);

                        CronTriggerImpl trigger = new CronTriggerImpl
                        {
                            CronExpressionString = jobInfo.CronExpression,
                            Name        = jobInfo.Id.ToString(),
                            Group       = $"{jobInfo.Id}TriggerGroup",
                            Description = jobInfo.Description,
                            TimeZone    = TimeZoneInfo.Local,
                        };

                        await scheduler.ScheduleJob(job, trigger);
                    }
                    catch (Exception e)
                    {
                        JobService.InsertLog(new JobLogEntity
                        {
                            JobId        = jobInfo.Id,
                            FireTime     = DateTime.Now,
                            FireDuration = 0,
                            FireState    = FireState.Error,
                            Content      = $"{jobInfo.Name}启用失败,异常信息:{e.Message}!",
                            CreateTime   = DateTime.Now
                        });
                        _log.Error($"JobId:{jobInfo.Id}|JobName:{jobInfo.Name}启用失败!", e);
                    }
                }
                else
                {
                    JobService.InsertLog(new JobLogEntity
                    {
                        JobId        = jobInfo.Id,
                        FireTime     = DateTime.Now,
                        FireDuration = 0,
                        FireState    = FireState.Error,
                        Content      = $"{jobInfo.Name}启用失败,请检查此Job执行类库是否上传到正确位置!",
                        CreateTime   = DateTime.Now
                    });
                }
            }
            else
            {
                JobService.InsertLog(new JobLogEntity
                {
                    JobId        = jobInfo.Id,
                    FireTime     = DateTime.Now,
                    FireDuration = 0,
                    FireState    = FireState.Error,
                    Content      = $"{jobInfo.Name}启用失败,Cron表达式错误!",
                    CreateTime   = DateTime.Now
                });
            }
        }
Ejemplo n.º 20
0
        private static async Task Start(ScheduleView view, PluginLoadContext lc)
        {
            //throw

            //在应用程序域中创建实例返回并保存在job中,这是最终调用任务执行的实例
            TaskBase instance = AssemblyHelper.CreateTaskInstance(lc, view.Schedule.Id, view.Schedule.AssemblyName, view.Schedule.ClassName);

            if (instance == null)
            {
                throw new InvalidCastException($"任务实例创建失败,请确认目标任务是否派生自TaskBase类型。程序集:{view.Schedule.AssemblyName},类型:{view.Schedule.ClassName}");
            }
            // instance.logger = new LogWriter(); ;
            JobDataMap map = new JobDataMap
            {
                new KeyValuePair <string, object> ("domain", lc),
                new KeyValuePair <string, object> ("instance", instance),
                new KeyValuePair <string, object> ("name", view.Schedule.Title),
                new KeyValuePair <string, object> ("params", ConvertParamsJson(view.Schedule.CustomParamsJson)),
                new KeyValuePair <string, object> ("keepers", view.Keepers),
                new KeyValuePair <string, object> ("children", view.Children)
            };

            try
            {
                IJobDetail job = JobBuilder.Create <RootJob>()
                                 .WithIdentity(view.Schedule.Id.ToString())
                                 .UsingJobData(map)
                                 .Build();

                //添加触发器
                var listener = new JobRunListener(view.Schedule.Id.ToString());
                listener.OnSuccess += StartedEvent;
                _scheduler.ListenerManager.AddJobListener(listener, KeyMatcher <JobKey> .KeyEquals(new JobKey(view.Schedule.Id.ToString())));

                if (view.Schedule.RunLoop)
                {
                    if (!CronExpression.IsValidExpression(view.Schedule.CronExpression))
                    {
                        throw new Exception("cron表达式验证失败");
                    }
                    CronTriggerImpl trigger = new CronTriggerImpl
                    {
                        CronExpressionString = view.Schedule.CronExpression,
                        Name        = view.Schedule.Title,
                        Key         = new TriggerKey(view.Schedule.Id.ToString()),
                        Description = view.Schedule.Remark
                    };
                    if (view.Schedule.StartDate.HasValue)
                    {
                        trigger.StartTimeUtc = TimeZoneInfo.ConvertTimeToUtc(view.Schedule.StartDate.Value);
                    }
                    if (view.Schedule.EndDate.HasValue)
                    {
                        trigger.EndTimeUtc = TimeZoneInfo.ConvertTimeToUtc(view.Schedule.EndDate.Value);
                    }
                    await _scheduler.ScheduleJob(job, trigger);
                }
                else
                {
                    DateTimeOffset start = TimeZoneInfo.ConvertTimeToUtc(DateTime.Now);
                    if (view.Schedule.StartDate.HasValue)
                    {
                        start = TimeZoneInfo.ConvertTimeToUtc(view.Schedule.StartDate.Value);
                    }
                    DateTimeOffset end = start.AddMinutes(1);
                    if (view.Schedule.EndDate.HasValue)
                    {
                        end = TimeZoneInfo.ConvertTimeToUtc(view.Schedule.EndDate.Value);
                    }
                    ITrigger trigger = TriggerBuilder.Create()
                                       .WithIdentity(view.Schedule.Id.ToString())
                                       .StartAt(start)
                                       .WithSimpleSchedule(x => x
                                                           .WithRepeatCount(1).WithIntervalInMinutes(1))
                                       .EndAt(end)
                                       .Build();
                    await _scheduler.ScheduleJob(job, trigger);
                }
            }
            catch (Exception ex)
            {
                throw new SchedulerException(ex);
            }
            LogHelper.Info($"任务[{view.Schedule.Title}]启动成功!", view.Schedule.Id);

            _ = Task.Run(() =>
            {
                while (true)
                {
                    var log = instance.ReadLog();
                    if (log != null)
                    {
                        LogManager.Queue.Write(new SystemLogEntity
                        {
                            Category   = log.Category,
                            Message    = log.Message,
                            ScheduleId = log.ScheduleId,
                            Node       = log.Node,
                            StackTrace = log.StackTrace,
                            TraceId    = log.TraceId,
                            CreateTime = log.CreateTime
                        });
                    }
                    else
                    {
                        Thread.Sleep(3000);
                    }
                }
            });
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main()
        {
            //ServiceBase[] ServicesToRun;
            //ServicesToRun = new ServiceBase[]
            //{
            //    new JobManager()
            //};
            //ServiceBase.Run(ServicesToRun);

            //test Code
            //FileJob job = new FileJob();
            //job.Execute(null);

            #region
            List <SchedulerConfigModel> list1 = SchedulerConfigDB.GetSchedulerRecord((int)JobEnum.DataType.UpdateData);
            if (list1.Count > 0)
            {
                for (int i = 0; i < list1.Count; i++)
                {
                    var              list      = list1[i];
                    SchedulerHelper  scheduler = new SchedulerHelper();
                    var              flag      = true;
                    SchedulerRequest request   = new SchedulerRequest();
                    request.JobName          = list.JobName;
                    request.JobGroup         = list.JobGroup;
                    request.TriggerName      = list.JobName + "Trigger";
                    request.TriggerGroupName = list.JobGroup + "Trigger";
                    request.CronTab          = list.CronTab;
                    request.StartTime        = list.StartTime;
                    if (list.EndTime != null)
                    {
                        request.EndTime = list.EndTime;
                    }
                    else
                    {
                        request.EndTime = null;
                    }
                    request.RequestType = list.RequestType;
                    request.RequestUrl  = list.RequestUrl;
                    var json = JsonConvert.SerializeObject(request);
                    scheduler.IsExistsDelJob(request.JobName, request.JobGroup);
                    if (flag)
                    {
                        IJobDetail jobDetail = JobBuilder.Create <FileJob>()
                                               .WithIdentity(request.JobName, request.JobGroup)
                                               .UsingJobData("jobJson", json)
                                               .Build();

                        CronTriggerImpl tigger = (CronTriggerImpl)TriggerBuilder.Create()
                                                 .WithIdentity(request.TriggerName, request.TriggerGroupName)
                                                 .WithCronSchedule(request.CronTab)
                                                 .ForJob(request.JobName, request.JobGroup)
                                                 .StartNow()
                                                 .Build();

                        DateTimeOffset dt = scheduler.scheduleJob(jobDetail, tigger);
                    }
                }
            }
            #endregion
        }