/// <summary> /// 创建类型Simple的触发器 /// </summary> /// <param name="entity"></param> /// <returns></returns> private ITrigger CreateSimpleTrigger(ScheduleEntity entity) { //作业触发器 if (entity.RunTimes.HasValue && entity.RunTimes > 0) { return(TriggerBuilder.Create() .WithIdentity(entity.JobName, entity.JobGroup) .StartAt(entity.BeginTime) //开始时间 .EndAt(entity.EndTime) //结束数据 .WithSimpleSchedule(x => { x.WithIntervalInSeconds(entity.IntervalSecond.Value) //执行时间间隔,单位秒 .WithRepeatCount(entity.RunTimes.Value) //执行次数、默认从0开始 .WithMisfireHandlingInstructionFireNow(); }) .ForJob(entity.JobName, entity.JobGroup)//作业名称 .Build()); } else { return(TriggerBuilder.Create() .WithIdentity(entity.JobName, entity.JobGroup) .StartAt(entity.BeginTime) //开始时间 .EndAt(entity.EndTime) //结束数据 .WithSimpleSchedule(x => { x.WithIntervalInSeconds(entity.IntervalSecond.Value) //执行时间间隔,单位秒 .RepeatForever() //无限循环 .WithMisfireHandlingInstructionFireNow(); }) .ForJob(entity.JobName, entity.JobGroup)//作业名称 .Build()); } }
/// <summary> /// 修改一个任务 /// </summary> /// <returns></returns> public async Task <ApiResult <string> > Modify(ScheduleEntity model) { var result = new ApiResult <string>() { statusCode = (int)ApiEnum.Error }; try { var redisTask = RedisHelper.Get <List <ScheduleEntity> >(KeyHelper.TaskSchedulerList); var task = redisTask.Where(m => m.JobId == model.JobId).FirstOrDefault(); if (task != null) { var job = new JobKey(model.JobName) { Group = model.JobGroup, Name = model.JobName }; //删除运行中的任务 await Scheduler.DeleteJob(job); //删除已存在 redisTask.Remove(task); //保存到Redis中 RedisHelper.Set(KeyHelper.TaskSchedulerList, redisTask); //新增到任务里面 await Add(model); } result.statusCode = (int)ApiEnum.Status; } catch (Exception ex) { result.message = ex.Message; } return(result); }
/// <summary> /// 查询任务 /// </summary> /// <param name="jobGroup"></param> /// <param name="jobName"></param> /// <returns></returns> public async Task <ApiResult <ScheduleEntity> > QueryJobAsync(string jobGroup, string jobName) { var res = new ApiResult <ScheduleEntity>() { }; var entity = new ScheduleEntity(); var jobKey = new JobKey(jobName, jobGroup); var jobDetail = await Scheduler.GetJobDetail(jobKey); var triggersList = await Scheduler.GetTriggersOfJob(jobKey); var triggers = triggersList.AsEnumerable().FirstOrDefault(); var intervalSeconds = (triggers as SimpleTriggerImpl)?.RepeatInterval.TotalSeconds; entity.RequestUrl = jobDetail.JobDataMap.GetString(Constant.REQUESTURL); entity.BeginTime = triggers.StartTimeUtc.LocalDateTime; entity.EndTime = triggers.EndTimeUtc?.LocalDateTime; entity.IntervalSecond = intervalSeconds.HasValue ? Convert.ToInt32(intervalSeconds.Value) : 0; entity.JobGroup = jobGroup; entity.JobName = jobName; entity.Cron = (triggers as CronTriggerImpl)?.CronExpressionString; entity.RunTimes = (triggers as SimpleTriggerImpl)?.RepeatCount; entity.TriggerType = triggers is SimpleTriggerImpl ? TriggerTypeEnum.Simple : TriggerTypeEnum.Cron; entity.RequestType = (RequestTypeEnum)int.Parse(jobDetail.JobDataMap.GetString(Constant.REQUESTTYPE)); entity.RequestParameters = jobDetail.JobDataMap.GetString(Constant.REQUESTPARAMETERS); entity.Headers = jobDetail.JobDataMap.GetString(Constant.HEADERS); entity.MailMessage = (MailMessageEnum)int.Parse(jobDetail.JobDataMap.GetString(Constant.MAILMESSAGE) ?? "0"); entity.Description = jobDetail.Description; res.data = entity; return(res); }
/// <summary> /// 添加一个工作调度 /// </summary> /// <param name="entity"></param> /// <returns></returns> public async Task <ApiResult <string> > AddScheduleJobAsync(ScheduleEntity entity) { var result = new ApiResult <string>() { statusCode = (int)ApiEnum.Error }; try { //检查任务是否已存在 var jobKey = new JobKey(entity.JobName, entity.JobGroup); if (await Scheduler.CheckExists(jobKey)) { result.message = "任务已存在"; return(result); } //http请求配置 var httpDir = new Dictionary <string, string>() { { "RequestUrl", entity.RequestUrl }, { "RequestParameters", entity.RequestParameters }, { "RequestType", ((int)entity.RequestType).ToString() }, { Constant.HEADERS, entity.Headers }, { Constant.MAILMESSAGE, ((int)entity.MailMessage).ToString() }, }; // 定义这个工作,并将其绑定到我们的IJob实现类 IJobDetail job = JobBuilder.CreateForAsync <HttpJob>() .SetJobData(new JobDataMap(httpDir)) .WithDescription(entity.Description) .WithIdentity(entity.JobName, entity.JobGroup) .Build(); // 创建触发器 ITrigger trigger; //校验是否正确的执行周期表达式 if (entity.TriggerType == TriggerTypeEnum.Cron)//CronExpression.IsValidExpression(entity.Cron)) { trigger = CreateCronTrigger(entity); } else { trigger = CreateSimpleTrigger(entity); } // 告诉Quartz使用我们的触发器来安排作业 await Scheduler.ScheduleJob(job, trigger); //判断是否暂停的任务 if (entity.TriggerState == TriggerState.Paused) { await Scheduler.PauseJob(new JobKey(entity.JobGroup, entity.JobName)); } result.statusCode = (int)ApiEnum.Status; } catch (Exception ex) { result.message = ex.Message; } return(result); }
/// <summary> /// 创建类型Cron的触发器 /// </summary> /// <param name="entity"></param> /// <returns></returns> private ITrigger CreateCronTrigger(ScheduleEntity entity) { // 作业触发器 return(TriggerBuilder.Create() .WithIdentity(entity.JobName, entity.JobGroup) .StartAt(entity.BeginTime) //开始时间 .EndAt(entity.EndTime) //结束时间 .WithCronSchedule(entity.Cron, cronScheduleBuilder => cronScheduleBuilder.WithMisfireHandlingInstructionFireAndProceed()) //指定cron表达式 .ForJob(entity.JobName, entity.JobGroup) //作业名称 .Build()); }
/// <summary> /// 添加一个任务 /// </summary> /// <returns></returns> public async Task <ApiResult <string> > Add(ScheduleEntity entity) { var result = new ApiResult <string>() { statusCode = (int)ApiEnum.Error }; try { //检查任务是否已存在 var jobKey = new JobKey(entity.JobName, entity.JobGroup); if (await Scheduler.CheckExists(jobKey)) { result.message = "任务已存在"; return(result); } //http请求配置 var httpDir = new Dictionary <string, string>() { { "RequestUrl", entity.RequestUrl }, { "RequestParameters", entity.RequestParameters }, { "RequestType", ((int)entity.RequestType).ToString() }, { Constant.HEADERS, entity.Headers }, { Constant.MAILMESSAGE, ((int)entity.MailMessage).ToString() }, }; // 定义这个工作,并将其绑定到我们的IJob实现类 IJobDetail job = JobBuilder.CreateForAsync <HttpJob>() .SetJobData(new JobDataMap(httpDir)) .WithDescription(entity.Description) .WithIdentity(entity.JobName, entity.JobGroup) .Build(); // 创建触发器 ITrigger trigger; //校验是否正确的执行周期表达式 if (entity.TriggerType == TriggerTypeEnum.Cron)//CronExpression.IsValidExpression(entity.Cron)) { trigger = CreateCronTrigger(entity); } else { trigger = CreateSimpleTrigger(entity); } // 告诉Quartz使用我们的触发器来安排作业 await Scheduler.ScheduleJob(job, trigger); //将作业增加到Redis里面 var redisTask = RedisHelper.Get <List <ScheduleEntity> >(KeyHelper.TaskSchedulerList); if (redisTask == null) { //实例数组 redisTask = new List <ScheduleEntity>(); } if (!redisTask.Any(m => m.JobId == entity.JobId)) { entity.JobId = Utils.GetOrderNumber(); redisTask.Add(entity); //保存到Redis中 RedisHelper.Set(KeyHelper.TaskSchedulerList, redisTask); } result.statusCode = (int)ApiEnum.Status; } catch (Exception ex) { result.message = ex.Message; } return(result); }