Example #1
0
        /// <summary>
        /// 创建类型Cron的触发器
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private ITrigger CreateCronTrigger(ScheduleEntityParam entity)
        {
            var triggerBuilder = GetTriggerBuilder(entity);

            // 作业触发器
            return(triggerBuilder
                   .WithCronSchedule(entity.Cron) //指定cron表达式
                   .Build());
        }
Example #2
0
 /// <summary>
 /// 创建TriggerBuilder
 /// </summary>
 /// <param name="entity"></param>
 /// <returns></returns>
 private TriggerBuilder GetTriggerBuilder(ScheduleEntityParam entity)
 {
     return(TriggerBuilder.Create()                        //创建
            .WithIdentity(entity.JobName, entity.JobGroup) // 标识
            .StartAt(entity.BeginTime)                     //开始时间
            .EndAt(entity.EndTime)                         //结束数据
            .WithPriority(entity.Priority)                 // 优先级 默认为5 相同执行时间越高越先执行
            .WithDescription(entity.Description ?? "")     //描述
            .ForJob(entity.JobName, entity.JobGroup));     //作业名称
 }
Example #3
0
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task <bool> AddTask(ScheduleEntityParam entity)
        {
            var sysQuartz = entity.MapTo <SysQuartz>();

            sysQuartz.CreatedTime      = DateTime.Now;
            sysQuartz.NextFireTime     = null;
            sysQuartz.PreviousFireTime = null;
            await SysQuartzDao.AddAsync(sysQuartz);

            var result = await SysQuartzDao.SaveChangesAsync();

            return(result > 0);
        }
Example #4
0
        /// <summary>
        /// 添加一个工作调度
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task <BaseResponseModel> AddScheduleJobAsync(ScheduleEntityParam entity)
        {
            var result = new ResponseModel <string>();

            try
            {
                if (!await CheckScheduleEntityParam(entity, result))
                {
                    return(result);
                }

                var jobDataMap = new Dictionary <string, string>()
                {
                    { QuartzConstant.NOTIFYEMAIL, entity.NotifyEmail },
                    { QuartzConstant.MAILMESSAGE, ((int)entity.MailMessage).ToString() },
                    { QuartzConstant.JOBTYPE, ((int)entity.JobType).ToString() },
                    { QuartzConstant.REQUESTPARAMETERS, entity.RequestParameters } //http Body 参数,Assembly 调用方法参数。
                };
                IJobDetail job;
                switch (entity.JobType)
                {
                case JobTypeEnum.Http:
                    job = AddHttpJob(entity, jobDataMap);
                    break;

                case JobTypeEnum.Assembly:
                    job = AddAssemblyJob(entity, jobDataMap);
                    break;

                case JobTypeEnum.None:
                default:
                    return(result.Fail("未选择任务类型"));

                    break;
                }

                //校验是否正确的执行周期表达式
                var trigger = entity.TriggerType == TriggerTypeEnum.Cron ? CreateCronTrigger(entity) : CreateSimpleTrigger(entity);

                await Scheduler.ScheduleJob(job, trigger);

                result.Succeed("添加任务成功");
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Fatal(ex, "添加任务失败");
                result.Fail(ResponseCode.UnknownEx, ex.Message, "");
            }

            return(result);
        }
        public async Task <ActionResult> ModifyJob(ScheduleEntityParam entity)
        {
            var result = await SchedulerCenter.StopOrDelScheduleJobAsync(new JobKey(entity.JobName, entity.JobGroup), true);

            if (!result.Success)
            {
                return(MyJson(result));
            }

            result = await SchedulerCenter.AddScheduleJobAsync(entity);

            if (result.Success)
            {
                result = await SysQuartzBll.ModifyTask(entity);
            }

            return(MyJson(result));
        }
Example #6
0
        /// <summary>
        /// 创建HttpJob
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="jobDataMap"></param>
        /// <returns></returns>
        private IJobDetail AddHttpJob(ScheduleEntityParam entity, Dictionary <string, string> jobDataMap)
        {
            //http请求配置
            jobDataMap.Add(QuartzConstant.REQUESTTYPE, entity.RequestMethod);
            jobDataMap.Add(QuartzConstant.REQUESTURL, entity.RequestPath);
            jobDataMap.Add(QuartzConstant.HEADERS, entity.Headers);

            // 定义这个工作,并将其绑定到我们的IJob实现类
            IJobDetail job = JobBuilder.Create <HttpJob>()
                             .SetJobData(new JobDataMap(jobDataMap))
                             .WithDescription(entity.Description)
                             .WithIdentity(entity.JobName, entity.JobGroup)
                                                //.StoreDurably() //孤立存储,指即使该JobDetail没有关联的Trigger,也会进行存储 也就是执行完成后,不删除
                             .RequestRecovery() //请求恢复,指应用崩溃后再次启动,会重新执行该作业
                             .Build();

            // 创建触发器
            return(job);
        }
        public async Task <ActionResult> AddTask(ScheduleEntityParam entity)
        {
            // 判断存在
            if (await SysQuartzBll.ExistTask(entity))
            {
                return(Fail("任务名称已存在,请进行修改原任务,或使用新名称"));
            }

            var result = await SchedulerCenter.AddScheduleJobAsync(entity);

            if (!result.Success)
            {
                return(MyJson(result));
            }

            var addResult = await SysQuartzBll.AddTask(entity);

            return(addResult ? Succeed() : Fail("添加失败"));
        }
Example #8
0
        /// <summary>
        /// 创建类型Simple的触发器
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private ITrigger CreateSimpleTrigger(ScheduleEntityParam entity)
        {
            var triggerBuilder = GetTriggerBuilder(entity);

            //作业触发器
            if (entity.RunTimes.HasValue && entity.RunTimes >= 0)
            {
                return(triggerBuilder
                       .WithSimpleSchedule(x =>
                                           x.WithIntervalInSeconds(entity.IntervalSecond ?? 1) //执行时间间隔,单位秒
                                           .WithRepeatCount(entity.RunTimes.Value))            //执行次数、默认从0开始
                       .Build());
            }

            return(triggerBuilder
                   .WithSimpleSchedule(x =>
                                       x.WithIntervalInSeconds(entity.IntervalSecond ?? 1) //执行时间间隔,单位秒
                                       .RepeatForever())                                   //无限循环

                   .Build());
        }
Example #9
0
        /// <summary>
        /// 调用本地方法
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="jobDataMap"></param>
        /// <returns></returns>
        private IJobDetail AddAssemblyJob(ScheduleEntityParam entity, Dictionary <string, string> jobDataMap)
        {
            // 格式 LionFrame.Quartz.Jobs.TestJob,LionFrame.Quartz
            var typeName = $"{entity.RequestPath}.{entity.RequestMethod},{entity.RequestPath}";
            var jobType  = Type.GetType(typeName);

            if (jobType == null)
            {
                throw new Exception("Job类未找到");
            }
            // 定义这个工作,并将其绑定到我们的IJob实现类
            var job = JobBuilder.Create(jobType)
                      .SetJobData(new JobDataMap(jobDataMap))
                      .WithDescription(entity.Description)
                      .WithIdentity(entity.JobName, entity.JobGroup)
                                         //.StoreDurably() //孤立存储,指即使该JobDetail没有关联的Trigger,也会进行存储 也就是执行完成后,不删除
                      .RequestRecovery() //请求恢复,指应用崩溃后再次启动,会重新执行该作业
                      .Build();

            // 创建触发器
            return(job);
        }
Example #10
0
        /// <summary>
        /// 修改任务
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task <BaseResponseModel> ModifyTask(ScheduleEntityParam entity)
        {
            var responseResult = new ResponseModel <string>();
            var result         = await SysQuartzDao.CurrentDbContext.SysQuartzs.Where(c => c.JobGroup == entity.JobGroup && c.JobName == entity.JobName).UpdateFromQueryAsync(c => new SysQuartz()
            {
                BeginTime         = entity.BeginTime,
                EndTime           = entity.EndTime,
                Cron              = entity.Cron ?? "",
                RunTimes          = entity.RunTimes ?? 1,
                IntervalSecond    = entity.IntervalSecond ?? 1,
                RequestPath       = entity.RequestPath,
                RequestMethod     = entity.RequestMethod,
                RequestParameters = entity.RequestParameters ?? "{}",
                Headers           = entity.Headers ?? "{}",
                Priority          = entity.Priority,
                Description       = entity.Description,
                NotifyEmail       = entity.NotifyEmail ?? "",
                MailMessage       = entity.MailMessage,
                TriggerState      = TriggerState.Normal,
            });

            return(result > 0 ? responseResult.Succeed() : responseResult.Fail("最终修改失败"));
        }
Example #11
0
        /// <summary>
        /// 检查参数是否符合要求
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        private async Task <bool> CheckScheduleEntityParam(ScheduleEntityParam entity, ResponseModel <string> result)
        {
            //检查任务是否已存在
            var jobKey = new JobKey(entity.JobName, entity.JobGroup);

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

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

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

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

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

            return(true);
        }
Example #12
0
        /// <summary>
        /// 判断任务名称是否已存在
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task <bool> ExistTask(ScheduleEntityParam entity)
        {
            var result = await SysQuartzDao.CurrentDbContext.SysQuartzs.AnyAsync(c => c.JobGroup == entity.JobGroup && c.JobName == entity.JobName);

            return(result);
        }