Esempio n. 1
0
 private static QuartzResult Exists(this QuartzOption QuartzOptions)
 {
     if (_taskList.Any(x => x.TaskName == QuartzOptions.TaskName && x.GroupName == QuartzOptions.GroupName))
     {
         return(QuartzResult.Error($"作业:{QuartzOptions.TaskName},分组:{QuartzOptions.GroupName}已经存在"));
     }
     return(QuartzResult.Ok("不存在"));
 }
Esempio n. 2
0
        /// <summary>
        /// 添加任务调度(指定IJob实现类)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="QuartzOptions"></param>
        /// <returns></returns>
        public static async Task <QuartzResult> AddJob <T>(this ISchedulerFactory schedulerFactory, QuartzOption QuartzOptions) where T : IJob
        {
            if (QuartzOptions is null)
            {
                throw new ArgumentNullException(nameof(QuartzOptions));
            }
            if (scheduler == null)
            {
                scheduler = schedulerFactory?.GetScheduler().Result;
            }
            try
            {
                //检查任务是否已存在
                if (await scheduler.CheckExists(new JobKey(QuartzOptions.TaskName, QuartzOptions.GroupName)))
                {
                    return(QuartzResult.Error($"任务 {QuartzOptions.TaskName},任务组 {QuartzOptions.GroupName} 已存在"));
                }
                // 定义这个工作,并将其绑定到我们的IJob实现类
                IJobDetail jobDetail = CreateJobDetail <T>(QuartzOptions);//JobBuilder.CreateForAsync<T>().WithIdentity(Option.TaskName, Option.GroupName).Build();
                // 创建触发器
                ITrigger trigger;
                if (QuartzOptions.IntervalType == IntervalType.Cron)
                {
                    if (!CronExpression.IsValidExpression(QuartzOptions.Interval))
                    {
                        return(QuartzResult.Error($"请确认表达式{QuartzOptions.Interval}是否正确!"));
                    }
                    trigger = QuartzOptions.CreateCronTrigger();
                }
                else
                {
                    trigger = CreateSimpleTrigger(QuartzOptions);
                }
                // 设置监听器
                //JobListener listener = new JobListener();
                //// IMatcher<JobKey> matcher = KeyMatcher<JobKey>.KeyEquals(job.Key);
                //scheduler.ListenerManager.AddJobListener(listener, GroupMatcher<JobKey>.AnyGroup());

                await scheduler.ScheduleJob(jobDetail, trigger);

                if (QuartzOptions.TaskStatus == TriggerState.Normal)
                {
                    await scheduler.Start();
                }
                else
                {
                    await schedulerFactory.Pause(QuartzOptions);
                }
                logger.LogDebug($"作业:{QuartzOptions.TaskName},目标:{QuartzOptions.TaskTarget},分组:{QuartzOptions.GroupName},状态为:{QuartzOptions.TaskStatus}");
                return(QuartzResult.Ok("添加成功"));
            }
            catch (Exception ex)
            {
                logger.LogError($"添加任务出错--{ex.StackTrace}");
                return(QuartzResult.Error($"添加任务出错--{ex.StackTrace}"));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 添加作业
        /// </summary>
        /// <param name="QuartzOptions"></param>
        /// <param name="schedulerFactory"></param>
        ///是否初始化,否=需要重新生成配置文件,是=不重新生成配置文件
        //trigger.JobDataMap, job.JobDataMap任选一个传参
        //trigger.JobDataMap.Add(typeof(HttpRequestJob).Name, Options.TaskData);
        /// <returns></returns>
        public static async Task <QuartzResult> AddJob(this ISchedulerFactory schedulerFactory, QuartzOption QuartzOptions)
        {
            if (QuartzOptions is null)
            {
                throw new ArgumentNullException(nameof(QuartzOptions));
            }
            if (scheduler == null)
            {
                scheduler = schedulerFactory?.GetScheduler().Result;
            }
            try
            {
                if (await scheduler.CheckExists(new JobKey(QuartzOptions.TaskName, QuartzOptions.GroupName)))
                {
                    return(QuartzResult.Error($"任务 {QuartzOptions.TaskName},任务组 {QuartzOptions.GroupName} 已存在"));
                }
                IJobDetail jobDetail = QuartzOptions.CreateJobDetail();
                if (jobDetail == null)
                {
                    return(QuartzResult.Error($"创建jobDetail 失败"));
                }
                ITrigger trigger = null;
                if (QuartzOptions.IntervalType == IntervalType.Cron)
                {
                    if (!CronExpression.IsValidExpression(QuartzOptions.Interval))
                    {
                        return(QuartzResult.Error($"请确认表达式{QuartzOptions.Interval}是否正确!"));
                    }

                    trigger = QuartzOptions.CreateCronTrigger();
                }
                else
                {
                    trigger = QuartzOptions.CreateSimpleTrigger();
                }

                _taskList.Add(QuartzOptions);

                await scheduler.ScheduleJob(jobDetail, trigger);

                if (QuartzOptions.TaskStatus == TriggerState.Normal)
                {
                    await scheduler.Start();
                }
                else
                {
                    await schedulerFactory.Pause(QuartzOptions);
                }
                logger.LogDebug($"作业:{QuartzOptions.TaskName},目标:{QuartzOptions.TaskTarget},分组:{QuartzOptions.GroupName},状态为:{QuartzOptions.TaskStatus}");
            }
            catch (Exception ex)
            {
                return(QuartzResult.Error(ex.Message));
            }
            return(QuartzResult.Ok($"作业:{QuartzOptions.TaskName},分组:{QuartzOptions.GroupName} 添加成功"));
        }
Esempio n. 4
0
        public async static Task <QuartzResult> ModifyTaskEntity(this ISchedulerFactory schedulerFactory, QuartzOption QuartzOptions, JobAction action)
        {
            QuartzOption options = null;

            switch (action)
            {
            case JobAction.Delete:
                for (int i = 0; i < _taskList.Count; i++)
                {
                    options = _taskList[i];
                    if (options.TaskName == QuartzOptions.TaskName && options.GroupName == QuartzOptions.GroupName)
                    {
                        _taskList.RemoveAt(i);
                    }
                }
                break;

            case JobAction.Modify:
                options = _taskList.Where(x => x.TaskName == QuartzOptions.TaskName && x.GroupName == QuartzOptions.GroupName).FirstOrDefault();
                //移除以前的配置
                if (options != null)
                {
                    _taskList.Remove(options);
                }
                //生成任务并添加新配置
                await schedulerFactory.AddJob(QuartzOptions);    //.GetAwaiter().GetResult();

                break;

            case JobAction.Pause:
            case JobAction.Start:
            case JobAction.Stop:
            case JobAction.StartNow:
                options = _taskList.Where(x => x.TaskName == QuartzOptions.TaskName && x.GroupName == QuartzOptions.GroupName).FirstOrDefault();
                if (action == JobAction.Pause)
                {
                    options.TaskStatus = TriggerState.Paused;
                }
                else if (action == JobAction.Stop)
                {
                    options.TaskStatus = (TriggerState)action;
                }
                else
                {
                    options.TaskStatus = TriggerState.Normal;
                }
                break;
            }
            //生成配置文件
            //FileQuartz.WriteJobConfig(_taskList);
            //FileQuartz.WriteJobAction(action, QuartzOptions.TaskName, QuartzOptions.GroupName, "操作对象:" + JsonConvert.SerializeObject(QuartzOptions));
            return(QuartzResult.Ok("成功"));
        }
Esempio n. 5
0
        /// <summary>
        /// 触发新增、删除、修改、暂停、启用、立即执行事件
        /// </summary>
        /// <param name="schedulerFactory"></param>
        /// <param name="action"></param>
        /// <param name="QuartzOptions"></param>
        /// <returns></returns>
        public static async Task <QuartzResult> TriggerAction(this ISchedulerFactory schedulerFactory, JobAction action, QuartzOption QuartzOptions)
        {
            try
            {
                List <JobKey> jobKeys = scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(QuartzOptions.GroupName)).Result.ToList();
                if (jobKeys == null || jobKeys.Count() == 0)
                {
                    return(QuartzResult.Error($"未找到分组[{QuartzOptions.GroupName}]"));
                }
                JobKey jobKey = jobKeys?.Where(x => x.Name == QuartzOptions.TaskName && x.Group == QuartzOptions.GroupName)?.FirstOrDefault();

                if (jobKey == null)
                {
                    return(QuartzResult.Error($"未找到触发器[{QuartzOptions.TaskName}]"));
                }
                var triggers = await scheduler.GetTriggersOfJob(jobKey);

                ITrigger trigger = triggers?.Where(x => x.JobKey.Name == QuartzOptions.TaskName && x.JobKey.Group == QuartzOptions.GroupName).FirstOrDefault();
                if (trigger == null)
                {
                    return(QuartzResult.Error($"未找到触发器[{QuartzOptions.TaskName}]"));
                }
                object result = null;
                switch (action)
                {
                case JobAction.Delete:
                case JobAction.Modify:
                    await scheduler.PauseTrigger(trigger.Key);

                    await scheduler.UnscheduleJob(trigger.Key);    // 移除触发器

                    await scheduler.DeleteJob(trigger.JobKey);

                    result = schedulerFactory.ModifyTaskEntity(QuartzOptions, action);
                    break;

                case JobAction.Pause:
                case JobAction.Stop:
                case JobAction.Start:
                    result = schedulerFactory.ModifyTaskEntity(QuartzOptions, action);
                    if (action == JobAction.Pause)
                    {
                        await scheduler.PauseTrigger(trigger.Key);
                    }
                    else if (action == JobAction.Start)
                    {
                        await scheduler.ResumeTrigger(trigger.Key);

                        //   await scheduler.RescheduleJob(trigger.Key, trigger);
                    }
                    else
                    {
                        await scheduler.Shutdown();
                    }
                    break;

                case JobAction.StartNow:
                    await scheduler.TriggerJob(jobKey);

                    break;
                }
                return(QuartzResult.Ok("成功"));
            }
            catch (Exception ex)
            {
                return(QuartzResult.Error($"失败 {ex.StackTrace}"));
            }
            finally
            {
            }
        }