C#编程之[C#][Quartz]帮助类
小标 2018-11-14 来源 : 阅读 1569 评论 0

摘要:本文主要向大家介绍了C#编程之[C#][Quartz]帮助类,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

本文主要向大家介绍了C#编程之[C#][Quartz]帮助类,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

/// 


    /// 任务处理帮助类
    /// 


    public class QuartzHelper
    {
        public QuartzHelper() { }

        public QuartzHelper(string quartzServer, string quartzPort)
        {
            Server = quartzServer;
            Port = quartzPort;
        }

        /// 


        /// 锁对象
        /// 


        private static readonly object Obj = new object();

        /// 


        /// 方案
        /// 


        private const string Scheme = "tcp";

        /// 


        /// 服务器的地址
        /// 


        public static  string Server { get; set; }

        /// 


        /// 服务器的端口
        /// 


        public static  string Port { get; set; }

        /// 


        /// 缓存任务所在程序集信息
        /// 


        private static readonly Dictionary

 AssemblyDict = new Dictionary();

        /// 
        /// 程序调度
        /// 

        private static IScheduler _scheduler;

        /// 
        /// 初始化任务调度对象
        /// 

        public static void InitScheduler()
        {
            try
            {
                lock (Obj)
                {
                    if (_scheduler != null) return;
                    //配置文件的方式,配置quartz实例
                    ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
                    _scheduler = schedulerFactory.GetScheduler();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// 
        /// 启用任务调度
        /// 启动调度时会把任务表中状态为“执行中”的任务加入到任务调度队列中
        /// 

        public static void StartScheduler()
        {
            try
            {
                if (_scheduler.IsStarted) return;
                //添加全局监听
                _scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener(), GroupMatcher.AnyGroup());
                _scheduler.Start();

                //获取所有执行中的任务
                List listTask = TaskHelper.GetAllTaskList().ToList();

                if (listTask.Count > 0)
                {
                    foreach (TaskModel taskUtil in listTask)
                    {
                        try
                        {
                            ScheduleJob(taskUtil);
                        }
                        catch (Exception e)
                        {
                          throw new Exception(taskUtil.TaskName,e);
                        }
                    }
                }              
            }
            catch (Exception ex)
            {
               throw new Exception(ex.Message);
            }
        }

        /// 
        /// 启用任务
        /// 任务信息
        /// 是否删除原有任务
        /// 返回任务trigger
        /// 

        public static void ScheduleJob(TaskModel task, bool isDeleteOldTask = false)
        {
            if (isDeleteOldTask)
            {
                //先删除现有已存在任务
                DeleteJob(task.TaskID.ToString());
            }
            //验证是否正确的Cron表达式
            if (ValidExpression(task.CronExpressionString))
            {
                IJobDetail job = new JobDetailImpl(task.TaskID.ToString(), GetClassInfo(task.AssemblyName, task.ClassName));
                //添加任务执行参数
                job.JobDataMap.Add("TaskParam", task.TaskParam);

                CronTriggerImpl trigger = new CronTriggerImpl
                {
                    CronExpressionString = task.CronExpressionString,
                    Name = task.TaskID.ToString(),
                    Description = task.TaskName
                };
                _scheduler.ScheduleJob(job, trigger);
                if (task.Status == TaskStatus.STOP)
                {
                    JobKey jk = new JobKey(task.TaskID.ToString());
                    _scheduler.PauseJob(jk);
                }
                else
                {
                    List list = GetNextFireTime(task.CronExpressionString, 5);
                    foreach (var time in list)
                    {
                        LogHelper.WriteLog(time.ToString(CultureInfo.InvariantCulture));
                    }
                }
            }
            else
            {
                throw new Exception(task.CronExpressionString + "不是正确的Cron表达式,无法启动该任务!");
            }
        }


        /// 
        /// 初始化 远程Quartz服务器中的,各个Scheduler实例。
        /// 提供给远程管理端的后台,用户获取Scheduler实例的信息。
        /// 

        public static void InitRemoteScheduler()
        {
            try
            {
                NameValueCollection properties = new NameValueCollection
                {
                    ["quartz.scheduler.instanceName"] = "ExampleQuartzScheduler",
                    ["quartz.scheduler.proxy"] = "true",
                    ["quartz.scheduler.proxy.address"] =string.Format("{0}://{1}:{2}/QuartzScheduler", Scheme, Server, Port)
                };

                ISchedulerFactory sf = new StdSchedulerFactory(properties);

                _scheduler = sf.GetScheduler();
            }
            catch (Exception ex)
            {
               throw new Exception(ex.StackTrace);
            }
        }

        /// 
        /// 删除现有任务
        /// 

        /// 
        public static void DeleteJob(string jobKey)
        {
            try
            {
                JobKey jk = new JobKey(jobKey);
                if (_scheduler.CheckExists(jk))
                {
                    //任务已经存在则删除
                    _scheduler.DeleteJob(jk);
                   
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

      

        /// 
        /// 暂停任务
        /// 

        /// 
        public static void PauseJob(string jobKey)
        {
            try
            {
                JobKey jk = new JobKey(jobKey);
                if (_scheduler.CheckExists(jk))
                {
                    //任务已经存在则暂停任务
                    _scheduler.PauseJob(jk);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// 
        /// 恢复运行暂停的任务
        /// 

        /// 任务key
        public static void ResumeJob(string jobKey)
        {
            try
            {
                JobKey jk = new JobKey(jobKey);
                if (_scheduler.CheckExists(jk))
                {
                    //任务已经存在则暂停任务
                    _scheduler.ResumeJob(jk);
                }
            }
            catch (Exception ex)
            {
              throw new Exception(ex.Message);
            }
        }

        ///  
        /// 获取类的属性、方法  
        /// 
  
        /// 程序集  
        /// 类名  
        private static Type GetClassInfo(string assemblyName, string className)
        {
            try
            {
                assemblyName = FileHelper.GetAbsolutePath(assemblyName + ".dll");
                Assembly assembly = null;
                if (!AssemblyDict.TryGetValue(assemblyName, out assembly))
                {
                    assembly = Assembly.LoadFrom(assemblyName);
                    AssemblyDict[assemblyName] = assembly;
                }
                Type type = assembly.GetType(className, true, true);
                return type;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// 
        /// 停止任务调度
        /// 

        public static void StopSchedule()
        {
            try
            {
                //判断调度是否已经关闭
                if (!_scheduler.IsShutdown)
                {
                    //等待任务运行完成
                    _scheduler.Shutdown(true);
                }
            }
            catch (Exception ex)
            {
               throw new Exception(ex.Message);
            }
        }

        /// 
        /// 校验字符串是否为正确的Cron表达式
        /// 

        /// 带校验表达式
        /// 
        public static bool ValidExpression(string cronExpression)
        {
            return CronExpression.IsValidExpression(cronExpression);
        }

        /// 
        /// 获取任务在未来周期内哪些时间会运行
        /// 

        /// Cron表达式
        /// 运行次数
        /// 运行时间段
        public static List GetNextFireTime(string CronExpressionString, int numTimes)
        {
            if (numTimes < 0)
            {
                throw new Exception("参数numTimes值大于等于0");
            }
            //时间表达式
            ITrigger trigger = TriggerBuilder.Create().WithCronSchedule(CronExpressionString).Build();
            IList dates = TriggerUtils.ComputeFireTimes(trigger as IOperableTrigger, null, numTimes);
            List list = new List();
            foreach (DateTimeOffset dtf in dates)
            {
                list.Add(TimeZoneInfo.ConvertTimeFromUtc(dtf.DateTime, TimeZoneInfo.Local));
            }
            return list;
        }


        public static object CurrentTaskList()
        {
            throw new NotImplementedException();
        }

        /// 
        /// 获取当前执行的Task 对象
        /// 

        /// 
        /// 
        public static TaskModel GetTaskDetail(IJobExecutionContext context)
        {
            TaskModel task = new TaskModel();

            if (context != null)
            {

                task.TaskID = Guid.Parse(context.Trigger.Key.Name);
                task.TaskName = context.Trigger.Description;
                task.RecentRunTime = DateTime.Now;
                task.TaskParam = context.JobDetail.JobDataMap.Get("TaskParam") != null ? context.JobDetail.JobDataMap.Get("TaskParam").ToString() : "";
            }
            return task;
        }
    }

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程