예제 #1
0
        ITrigger CreateTrigger(RecurringSchedule message, IJobDetail jobDetail, TriggerKey triggerKey)
        {
            TimeZoneInfo tz = TimeZoneInfo.Local;

            if (!string.IsNullOrWhiteSpace(message.TimeZoneId) && message.TimeZoneId != tz.Id)
            {
                tz = TimeZoneInfo.FindSystemTimeZoneById(message.TimeZoneId);
            }

            TriggerBuilder triggerBuilder = TriggerBuilder.Create()
                                            .ForJob(jobDetail)
                                            .WithIdentity(triggerKey)
                                            .StartAt(message.StartTime)
                                            .WithCronSchedule(message.CronExpression, x =>
            {
                x.InTimeZone(tz);
                switch (message.MisfirePolicy)
                {
                case MissedEventPolicy.Skip:
                    x.WithMisfireHandlingInstructionDoNothing();
                    break;

                case MissedEventPolicy.Send:
                    x.WithMisfireHandlingInstructionFireAndProceed();
                    break;
                }
            });

            if (message.EndTime.HasValue)
            {
                triggerBuilder.EndAt(message.EndTime);
            }

            return(triggerBuilder.Build());
        }
예제 #2
0
        /// <summary>
        /// 开启任务
        /// </summary>
        public void Start()
        {
            ISchedulerFactory factory   = new StdSchedulerFactory();
            IScheduler        scheduler = factory.GetScheduler().Result;

            foreach (TaskInfo info in tasks)
            {
                if (info.IsEnabled)
                {
                    Type type = Type.GetType(info.TaskType);
                    if (type != null)
                    {
                        string     name      = type.Name + "_trigger";
                        IJobDetail jobDetail = JobBuilder.Create(typeof(QuartzTask)).WithIdentity(type.Name).Build();
                        jobDetail.JobDataMap.Add(new KeyValuePair <string, object>("Id", info.Id));
                        TriggerBuilder builder = TriggerBuilder.Create().WithIdentity(name).WithCronSchedule(info.TaskRule);
                        if (info.StartDate > DateTime.MinValue)
                        {
                            builder.StartAt(new DateTimeOffset(info.StartDate));
                        }
                        DateTime?endDate   = info.EndDate;
                        DateTime startDate = info.StartDate;
                        if (endDate.HasValue ? (endDate.GetValueOrDefault() > startDate) : false)
                        {
                            DateTime?nullable2 = info.EndDate;
                            builder.EndAt(nullable2.HasValue ? new DateTimeOffset?(nullable2.GetValueOrDefault()) : null);
                        }
                        ICronTrigger trigger  = (ICronTrigger)builder.Build();
                        DateTime     dateTime = scheduler.ScheduleJob(jobDetail, trigger).Result.DateTime;
                        info.NextDate = new DateTime?(TimeZoneInfo.ConvertTime(dateTime, trigger.TimeZone));
                    }
                }
            }
            scheduler.Start();
        }
예제 #3
0
 /// <summary>
 /// 设置作业结束时间
 /// </summary>
 private void SetEndTime(TriggerBuilder builder, JobBase job)
 {
     if (job.GetEndTime() == null)
     {
         return;
     }
     builder.EndAt(job.GetEndTime().SafeValue());
 }
예제 #4
0
        /// <summary>
        /// 启动任务
        /// </summary>
        public void Start()
        {
            if (_tasks.Count() == 0)
            {
                return;
            }

            TaskService       taskService = new TaskService();
            ISchedulerFactory sf          = new StdSchedulerFactory();
            IScheduler        sched       = sf.GetScheduler();

            foreach (var task in _tasks)
            {
                if (!task.Enabled)
                {
                    continue;
                }

                Type type = Type.GetType(task.ClassType);
                if (type == null)
                {
                    continue;
                }

                string triggerName = type.Name + "_trigger";

                IJobDetail job = JobBuilder.Create(typeof(QuartzTask))
                                 .WithIdentity(type.Name)
                                 .Build();

                job.JobDataMap.Add(new KeyValuePair <string, object>("Id", task.Id));


                TriggerBuilder tb = TriggerBuilder.Create()
                                    .WithIdentity(triggerName)
                                    .WithCronSchedule(task.TaskRule);

                if (task.StartDate > DateTime.MinValue)
                {
                    tb.StartAt(new DateTimeOffset(task.StartDate));
                }

                if (task.EndDate > task.StartDate)
                {
                    tb.EndAt(task.EndDate);
                }

                ICronTrigger trigger = (ICronTrigger)tb.Build();
                DateTime     ft      = sched.ScheduleJob(job, trigger).DateTime;
                task.NextStart = TimeZoneInfo.ConvertTime(ft, trigger.TimeZone);
            }

            sched.Start();
        }
예제 #5
0
        public void Update(TaskDetail task)
        {
            if (task == null)
            {
                return;
            }
            int index = _tasks.FindIndex((TaskDetail n) => n.Id == task.Id);

            if (_tasks[index] == null)
            {
                return;
            }
            task.ClassType     = _tasks[index].ClassType;
            task.LastEnd       = _tasks[index].LastEnd;
            task.LastStart     = _tasks[index].LastStart;
            task.LastIsSuccess = _tasks[index].LastIsSuccess;
            _tasks[index]      = task;
            Type type = Type.GetType(task.ClassType);

            if (type == null)
            {
                return;
            }
            Remove(type.Name);
            if (!task.Enabled)
            {
                return;
            }
            string            name             = type.Name + "_trigger";
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
            IScheduler        scheduler        = schedulerFactory.GetScheduler();
            IJobDetail        jobDetail        = JobBuilder.Create(typeof(QuartzTask)).WithIdentity(type.Name).Build();

            jobDetail.JobDataMap.Add(new KeyValuePair <string, object>("Id", task.Id));
            TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithIdentity(name).WithCronSchedule(task.TaskRule);

            if (task.StartDate > DateTime.MinValue)
            {
                triggerBuilder.StartAt(new DateTimeOffset(task.StartDate));
            }
            if (task.EndDate.HasValue && task.EndDate > task.StartDate)
            {
                TriggerBuilder arg_233_0 = triggerBuilder;
                DateTime?      endDate   = task.EndDate;
                arg_233_0.EndAt(endDate.HasValue ? new DateTimeOffset?(endDate.GetValueOrDefault()) : null);
            }
            var      cronTrigger = (ICronTrigger)triggerBuilder.Build();
            DateTime dateTime    = scheduler.ScheduleJob(jobDetail, cronTrigger).DateTime;

            task.NextStart = TimeZoneInfo.ConvertTime(dateTime, cronTrigger.TimeZone);
        }
예제 #6
0
 /// <summary>
 /// 更新任务
 /// </summary>
 /// <param name="task"></param>
 public void Update(TaskInfo task)
 {
     if (task != null)
     {
         int num = tasks.FindIndex(n => n.Id == task.Id);
         if (tasks[num] != null)
         {
             task.TaskType      = tasks[num].TaskType;
             task.LastEndDate   = tasks[num].LastEndDate;
             task.LastStartDate = tasks[num].LastStartDate;
             task.LastSuccess   = tasks[num].LastSuccess;
             tasks[num]         = task;
             Type type = Type.GetType(task.TaskType);
             if (type != null)
             {
                 this.Remove(type.Name);
                 if (task.IsEnabled)
                 {
                     string            name      = type.Name + "_trigger";
                     ISchedulerFactory factory   = new StdSchedulerFactory();
                     IScheduler        scheduler = factory.GetScheduler().Result;
                     IJobDetail        jobDetail = JobBuilder.Create(typeof(QuartzTask)).WithIdentity(type.Name).Build();
                     jobDetail.JobDataMap.Add(new KeyValuePair <string, object>("Id", task.Id));
                     TriggerBuilder builder = TriggerBuilder.Create().WithIdentity(name).WithCronSchedule(task.TaskRule);
                     if (task.StartDate > DateTime.MinValue)
                     {
                         builder.StartAt(new DateTimeOffset(task.StartDate));
                     }
                     if (task.EndDate.HasValue)
                     {
                         DateTime?endDate   = task.EndDate;
                         DateTime startDate = task.StartDate;
                         if (endDate.HasValue ? (endDate.GetValueOrDefault() > startDate) : false)
                         {
                             DateTime?nullable3 = task.EndDate;
                             builder.EndAt(nullable3.HasValue ? new DateTimeOffset?(nullable3.GetValueOrDefault()) : null);
                         }
                     }
                     ICronTrigger trigger  = (ICronTrigger)builder.Build();
                     DateTime     dateTime = scheduler.ScheduleJob(jobDetail, trigger).Result.DateTime;
                     task.NextDate = new DateTime?(TimeZoneInfo.ConvertTime(dateTime, trigger.TimeZone));
                 }
             }
         }
     }
 }
예제 #7
0
        /// <summary>
        /// 创建CronTrigger
        /// </summary>
        /// <returns></returns>
        public static ICronTrigger CreateCronTrigger(TriggerItem triggerItem)
        {
            TriggerBuilder triggerBuilder = TriggerBuilder.Create();

            if (!string.IsNullOrEmpty(triggerItem.StartTime))
            {
                triggerBuilder = triggerBuilder.StartAt(Convert.ToDateTime(triggerItem.StartTime));
            }
            if (!string.IsNullOrEmpty(triggerItem.EndTime))
            {
                triggerBuilder = triggerBuilder.EndAt(Convert.ToDateTime(triggerItem.EndTime));
            }
            triggerBuilder = triggerBuilder.WithCronSchedule(triggerItem.CronExpression);
            ICronTrigger trigger = (ICronTrigger)triggerBuilder
                                   .WithCronSchedule(triggerItem.CronExpression)
                                   .WithIdentity(triggerItem.Name, triggerItem.Group)
                                   .Build();

            return(trigger);
        }
예제 #8
0
        public static ITrigger GetTrigger(this SnapshotRule rule)
        {
            TriggerBuilder builder = TriggerBuilder.Create()
                                     .WithIdentity(rule.ToString(), "SnapshotJob")
                                     .WithCronSchedule(rule.GeneratedCron)
                                     .StartAt(rule.PeriodStart)
                                     .UsingJobData("RuleId", rule.Id)
                                     .WithDescription(rule.ToString());

            if (rule.PeriodEndEnabled)
            {
                builder = builder.EndAt(rule.PeriodEnd);
            }

            if (rule.HasCalendar())
            {
                builder = builder.ModifiedByCalendar(rule.GetCalendarName());
            }

            return(builder.Build());
        }
예제 #9
0
        public void Start()
        {
            if (_tasks.Count() == 0)
            {
                return;
            }
            new TaskService();
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
            IScheduler        scheduler        = schedulerFactory.GetScheduler();

            foreach (TaskDetail current in _tasks)
            {
                if (current.Enabled)
                {
                    Type type = Type.GetType(current.ClassType);
                    if (!(type == null))
                    {
                        string     name      = type.Name + "_trigger";
                        IJobDetail jobDetail = JobBuilder.Create(typeof(QuartzTask)).WithIdentity(type.Name).Build();
                        jobDetail.JobDataMap.Add(new KeyValuePair <string, object>("Id", current.Id));
                        TriggerBuilder triggerBuilder =
                            TriggerBuilder.Create().WithIdentity(name).WithCronSchedule(current.TaskRule);
                        if (current.StartDate > DateTime.MinValue)
                        {
                            triggerBuilder.StartAt(new DateTimeOffset(current.StartDate));
                        }
                        if (current.EndDate > current.StartDate)
                        {
                            TriggerBuilder arg_14A_0 = triggerBuilder;
                            DateTime?      endDate   = current.EndDate;
                            arg_14A_0.EndAt(endDate.HasValue ? new DateTimeOffset?(endDate.GetValueOrDefault()) : null);
                        }
                        var      cronTrigger = (ICronTrigger)triggerBuilder.Build();
                        DateTime dateTime    = scheduler.ScheduleJob(jobDetail, cronTrigger).DateTime;
                        current.NextStart = TimeZoneInfo.ConvertTime(dateTime, cronTrigger.TimeZone);
                    }
                }
            }
            scheduler.Start();
        }
예제 #10
0
        /// <summary>
        /// 开始任务
        /// </summary>
        public void Start()
        {
            var taskService = DIContainer.Resolve <IQuartzTaskService>();

            if (_tasks == null)
            {
                _tasks = taskService.QuartzTasks.ToList();
            }

            if (_tasks.Count == 0)
            {
                return;
            }

            var taskScheduler = DIContainer.Resolve <ITaskScheduler>();

            foreach (var task in _tasks)
            {
                if (!task.Enabled)
                {
                    continue;
                }

                Type type = Type.GetType(task.ClassType);
                if (type == null)
                {
                    continue;
                }

                string triggerName = type.Name + "_trigger";

                IJobDetail job = JobBuilder.Create(typeof(JobDetail))
                                 .WithIdentity(type.Name)
                                 .Build();

                job.JobDataMap.Add(new KeyValuePair <string, object>("Id", task.Id));


                TriggerBuilder tb = TriggerBuilder.Create()
                                    .WithIdentity(triggerName)
                                    .WithCronSchedule(task.TaskRule);

                if (task.NextStart.HasValue)
                {
                    tb.StartAt(new DateTimeOffset(task.NextStart.Value));
                }
                else if (task.StartDate > DateTime.MinValue)
                {
                    tb.StartAt(new DateTimeOffset(task.StartDate));
                }

                if (task.EndDate > task.StartDate)
                {
                    tb.EndAt(task.EndDate);
                }

                ICronTrigger trigger   = (ICronTrigger)tb.Build();
                DateTime     nextStart = sched.ScheduleJob(job, trigger).LocalDateTime;

                if (task.NextStart == null || task.NextStart < nextStart)
                {
                    task.NextStart = nextStart;
                    taskScheduler.SaveTaskStatus(task);
                }
            }

            sched.Start();
        }
예제 #11
0
        /// <summary>
        /// 更新任务
        /// </summary>
        /// <param name="task"></param>
        public void Update(QuartzTask task)
        {
            if (task == null)
            {
                return;
            }

            int index = _tasks.FindIndex(n => n.Id == task.Id);

            if (_tasks[index] == null)
            {
                return;
            }

            task.ClassType     = _tasks[index].ClassType;
            task.LastEnd       = _tasks[index].LastEnd;
            task.LastStart     = _tasks[index].LastStart;
            task.LastIsSuccess = _tasks[index].LastIsSuccess;

            _tasks[index] = task;

            Type type = Type.GetType(task.ClassType);

            if (type == null)
            {
                return;
            }

            Remove(type.Name);

            if (!task.Enabled)
            {
                return;
            }

            string triggerName = type.Name + "_trigger";

            IJobDetail job = JobBuilder.Create(typeof(JobDetail))
                             .WithIdentity(type.Name)
                             .Build();

            job.JobDataMap.Add(new KeyValuePair <string, object>("Id", task.Id));


            TriggerBuilder tb = TriggerBuilder.Create()
                                .WithIdentity(triggerName)
                                .WithCronSchedule(task.TaskRule);

            if (task.NextStart.HasValue)
            {
                tb.StartAt(new DateTimeOffset(task.NextStart.Value));
            }
            else if (task.StartDate > DateTime.MinValue)
            {
                tb.StartAt(new DateTimeOffset(task.StartDate));
            }

            if (task.EndDate.HasValue && task.EndDate > task.StartDate)
            {
                tb.EndAt(task.EndDate);
            }

            ICronTrigger trigger = (ICronTrigger)tb.Build();

            DateTime nextStart = sched.ScheduleJob(job, trigger).LocalDateTime;

            if (task.NextStart.HasValue && task.NextStart < nextStart)
            {
                task.NextStart = nextStart;
            }
        }
예제 #12
0
        /// <summary>
        /// 初始化并启动
        /// </summary>
        public void Startup()
        {
            Task.Run(async() => {
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
                _factory   = new StdSchedulerFactory(props);
                _scheduler = await _factory.GetScheduler();
                _scheduler.Context.Add("IServiceProvider", _provider);
                await _scheduler.Start();

                //读取数据库中所有定时任务
                var tasks = await _service.GetListAsync(new Domain.Entity.System.TimedTaskSearch {
                    IsDeleted = false
                }, null);

                //加载程序集
                assemblies = tasks.Select(x => x.AssemblyName).Distinct().Select(name => AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(name))).ToList();

                foreach (var task in tasks.Where(x => x.Status != Domain.Enum.System.EmTimedTaskStatus.Disable && x.Status != Domain.Enum.System.EmTimedTaskStatus.Expired))
                {
                    //处理过期任务
                    if (task.ValidEndTime < DateTime.Now)
                    {
                        await _service.UpdateTaskStatusAsync(task.Id, new {
                            Status = Domain.Enum.System.EmTimedTaskStatus.Expired
                        });
                        continue;
                    }

                    var assembly = assemblies.FirstOrDefault(x => x.FullName.Split(',')[0].Equals(task.AssemblyName));
                    if (assembly == null)
                    {
                        //未正确加载程序集
                        await _service.UpdateTaskStatusAsync(task.Id, new
                        {
                            Status = Domain.Enum.System.EmTimedTaskStatus.Abnormal
                        });
                        continue;
                    }

                    var type = assembly.DefinedTypes.FirstOrDefault(x => x.FullName.Equals(task.TypeName));
                    if (type == null)
                    {
                        //未正确加载类型
                        await _service.UpdateTaskStatusAsync(task.Id, new
                        {
                            Status = Domain.Enum.System.EmTimedTaskStatus.Abnormal
                        });
                        continue;
                    }

                    // 定义一个 Job
                    IJobDetail job = JobBuilder.Create(type)
                                     .WithIdentity(task.Name, task.Group)
                                     .UsingJobData("TaskId", task.Id)
                                     .Build();

                    // 定义一个触发器
                    TriggerBuilder builder = TriggerBuilder.Create().WithIdentity(task.Name, task.Group);
                    if (task.ValidStartTime <= DateTime.Now)
                    {
                        builder = builder.StartNow();
                    }
                    else
                    {
                        builder = builder.StartAt(task.ValidStartTime);
                    }
                    builder = builder.EndAt(task.ValidEndTime);

                    //Cron
                    builder = builder.WithCronSchedule(task.Cron);

                    ITrigger trigger = builder.Build();

                    //加入Job
                    await _scheduler.ScheduleJob(job, trigger);
                }
            });
        }
예제 #13
0
        private static void ScheduleJobs()
        {
            int priority = Jobs.Count;

            foreach (var tsk in Jobs.Where(x => x.TaskType == "S" && x.Status == "Queued")) // O - On Demand ; S- Scheduled.
            {
                var schedule = Schedules.FirstOrDefault(x => x.taskID == tsk.taskID);
                var client   = Machines.FirstOrDefault(x => x.ID == tsk.ClientID);

                IJobDetail job = JobBuilder.Create <Job>().WithIdentity(tsk.TaskName, tsk.ClientID.ToString()).Build();
                job.JobDataMap["command"]  = tsk.Command;
                job.JobDataMap["taskname"] = tsk.TaskName;
                job.JobDataMap["TaskId"]   = tsk.taskID;
                if (client != null)
                {
                    job.JobDataMap["remotepc"] = "\\\\" + client.HostName;
                    job.JobDataMap["username"] = client.Username;
                    job.JobDataMap["password"] = client.Password;
                }


                if (schedule != null)
                {
                    TriggerBuilder tb = TriggerBuilder.Create();
                    tb.WithIdentity(tsk.TaskName);

                    if (schedule.repeatforever <= 0)
                    {
                        tb.WithSimpleSchedule(a => a.WithIntervalInHours(schedule.intHours));
                        tb.WithSimpleSchedule(a => a.WithIntervalInSeconds(schedule.intSec));
                        tb.WithSimpleSchedule(a => a.WithIntervalInMinutes(schedule.intMin));
                    }
                    else
                    {
                        if (schedule.intHours > 0)
                        {
                            tb.WithSimpleSchedule(a => a.WithIntervalInHours(schedule.intHours).RepeatForever());
                        }
                        if (schedule.intHours > 0)
                        {
                            tb.WithSimpleSchedule(a => a.WithIntervalInSeconds(schedule.intSec).RepeatForever());
                        }
                        if (schedule.intHours > 0)
                        {
                            tb.WithSimpleSchedule(a => a.WithIntervalInMinutes(schedule.intMin).RepeatForever());
                        }
                    }

                    if (schedule.startAt != null)
                    {
                        tb.StartAt(new DateTimeOffset((DateTime)schedule.startAt));
                    }
                    if (schedule.endAt != null)
                    {
                        tb.EndAt(new DateTimeOffset((DateTime)schedule.endAt));
                    }



                    tb.ForJob(job);
                    ITrigger trigger = tb.Build();
                    Scheduler.ScheduleJob(job, trigger);
                }
            }
        }
예제 #14
0
        private void scheduleTask(ScheduledTask task)
        {
            if (!string.IsNullOrEmpty(task.ServerName) && task.ServerName.ToLower(CultureInfo.GetCultureInfo("en-US")) != System.Environment.MachineName.ToLower(CultureInfo.GetCultureInfo("en-US")))
            {
                return;
            }
            JobKey jobKey = new JobKey(task.Name);

            if (!task.Enabled)
            {
                if (_scheduler.CheckExists(jobKey))
                {
                    _scheduler.DeleteJob(jobKey);
                }
                return;
            }
            TriggerKey     triggerkey     = new TriggerKey(string.Format("{0}_trigger", task.Name));
            TriggerBuilder triggerBuilder = null;

            if (!_scheduler.CheckExists(triggerkey))
            {
                triggerBuilder = TriggerBuilder.Create().WithIdentity(triggerkey);
            }
            else
            {
                ICronTrigger oldTrigger = (ICronTrigger)_scheduler.GetTrigger(triggerkey);
                if (oldTrigger.CronExpressionString == task.CronExpression)
                {
                    return;
                }
                triggerBuilder = oldTrigger.GetTriggerBuilder();
            }

            TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(PxConfigurationManager.PxConfig.Schedule.TimeZoneId);

            switch (task.MissedScheduleAction)
            {
            case MissedScheduleActionType.RunLatest:
                triggerBuilder = triggerBuilder.WithCronSchedule(task.CronExpression, x => x.InTimeZone(timeZoneInfo).WithMisfireHandlingInstructionFireAndProceed());
                break;

            case MissedScheduleActionType.RunAll:
                triggerBuilder = triggerBuilder.WithCronSchedule(task.CronExpression, x => x.InTimeZone(timeZoneInfo).WithMisfireHandlingInstructionIgnoreMisfires());
                break;

            case MissedScheduleActionType.NoAction:
            default:
                triggerBuilder = triggerBuilder.WithCronSchedule(task.CronExpression, x => x.InTimeZone(timeZoneInfo).WithMisfireHandlingInstructionDoNothing());
                break;
            }

            if (task.StartDate != null && (DateTime)task.StartDate != DateTime.MinValue)
            {
                triggerBuilder = triggerBuilder.StartAt(new DateTimeOffset(task.StartDate.Value));
            }
            else
            {
                triggerBuilder = triggerBuilder.StartAt(new DateTimeOffset(DateTime.Now));
            }
            if (task.EndDate != null && (DateTime)task.EndDate != DateTime.MinValue)
            {
                triggerBuilder = triggerBuilder.EndAt(new DateTimeOffset((DateTime)task.EndDate));
            }

            IJobDetail job = JobBuilder.Create <PxScheduledTask>().WithIdentity(jobKey).RequestRecovery().Build();

            job.JobDataMap.Put("ScheduledTask", task);
            ICronTrigger trigger = (ICronTrigger)triggerBuilder.ForJob(job).Build();

            if (!_scheduler.CheckExists(triggerkey))
            {
                _scheduler.ScheduleJob(job, trigger);
            }
            else
            {
                _scheduler.RescheduleJob(triggerkey, trigger);
            }
        }
예제 #15
0
        public async Task CreateOrUpdate(JobCreateOrUpdateRequest request)
        {
            request.Name  = request.Name.Trim();
            request.Group = request.Group.Trim();

            JobKey key = new JobKey(request.Name, request.Group);

            if (await _scheduler.CheckExists(key))
            {
                if (!request.IsUpdate)
                {
                    throw new Exception("已存在相同名称的任务");                    // 新增时,存在相同任务,不创建
                }
                else
                {
                    await _scheduler.DeleteJob(key);    // 更新时,先删除,再创建
                }
            }
            ;

            /******Data*****/
            JobDataMap dataMap = new JobDataMap();

            dataMap.Put(DataKeys.HttpMethod, request.HttpMethod);
            dataMap.Put(DataKeys.RequestUrl, request.RequestUrl);
            dataMap.Put(DataKeys.TriggerType, request.TriggerType);
            dataMap.Put(DataKeys.RepeatCount, request.RepeatCount);
            dataMap.Put(DataKeys.Interval, request.Interval);
            dataMap.Put(DataKeys.IntervalType, request.IntervalType);
            dataMap.Put(DataKeys.Cron, request.Cron);
            dataMap.Put(DataKeys.RequestBody, request.RequestBody);
            dataMap.Put(DataKeys.CreateTime, DateTime.Now.ToString());
            dataMap.Put(DataKeys.StartTime, request.StartTime.ToString());
            dataMap.Put(DataKeys.EndTime, request.EndTime.HasValue ? request.EndTime.Value.ToString() : string.Empty);

            /******Job*****/
            IJobDetail job = JobBuilder.Create <HttpJob>()
                             .StoreDurably(true) // 是否持久化, 无关联触发器时是否移除,false:移除
                             .RequestRecovery()  // 重启后是否恢复任务
                             .WithDescription(request.Description ?? string.Empty)
                             .WithIdentity(request.Name, request.Group)
                             .UsingJobData(dataMap)
                             .Build();

            /******Trigger*****/
            TriggerBuilder builder = TriggerBuilder.Create()
                                     .WithIdentity(request.Name, request.Group)
                                     .StartAt(request.StartTime.Value)
                                     .ForJob(job);

            if (request.EndTime.HasValue)
            {
                builder.EndAt(request.EndTime.Value);
            }
            if (request.TriggerType == (int)TriggerTypeEnum.Simple)
            {
                builder.WithSimpleSchedule(simple =>
                {
                    if (request.IntervalType == (int)IntervalTypeEnum.Second)
                    {
                        simple.WithIntervalInSeconds(request.Interval);
                    }
                    if (request.IntervalType == (int)IntervalTypeEnum.Minute)
                    {
                        simple.WithIntervalInMinutes(request.Interval);
                    }
                    if (request.IntervalType == (int)IntervalTypeEnum.Hour)
                    {
                        simple.WithIntervalInHours(request.Interval);
                    }
                    if (request.IntervalType == (int)IntervalTypeEnum.Day)
                    {
                        simple.WithIntervalInHours(request.Interval * 24);
                    }

                    if (request.RepeatCount > 0)
                    {
                        simple.WithRepeatCount(request.RepeatCount);
                    }
                    else
                    {
                        simple.RepeatForever();
                    }
                    simple.WithMisfireHandlingInstructionFireNow(); // 如果延迟执行了
                });
            }
            else
            {
                builder.WithCronSchedule(request.Cron, cron =>
                {
                    cron.WithMisfireHandlingInstructionFireAndProceed();
                });
            }

            ITrigger trigger = builder.Build();

            await _scheduler.ScheduleJob(job, trigger); // 加入调度,并持久化

            FlushCache();
        }
예제 #16
0
 public TriggerHelper EndAt(DateTimeOffset endTimeUtc)
 {
     trigger.EndAt(endTimeUtc);
     return(this);
 }