动态添加定时器Quartz

2020-06-12  本文已影响0人  飞天猪Pony

调用定时器,比如说对不同的视频创建一个定时器。VideoID:视频ID

/// <summary>
/// 为某一个视频添加定时通知任务
/// </summary>
private static void QuartzLive(int VideoID)
{
      //在某个时间点内执行
      string timestr = DateTime.Now.AddSeconds(30).ToString("yyyy-MM-dd HH:mm:ss");
      //将时间转为Cron
      string cron = TimeToCron.TimeToQuartzCron(timestr);
      string ID = VideoID.ToString();
      QuartzConfigHelper.StartJob(ID, typeof(QuartzVideoStartLive), ID, cron );
}

定时器Helper类

public class QuartzConfigHelper
    {

        private static ISchedulerFactory sf = new StdSchedulerFactory();    //创建一个调度器工厂
        private static String JOB_GROUP_NAME = "QuartzJobGroupName";
        private static String TRIGGER_GROUP_NAME = "QuartzTriggerGroupName";
        private static IScheduler sched;            //创建一个调度器    
        #region 动态创建和编辑任务
        /// <summary>
        /// 创建一个定时任务
        /// </summary>
        /// <param name="jobName"></param>
        /// <param name="jobType"></param>
        /// <param name="jobkey"></param>
        /// <param name="time"></param>
        public static void StartJob(string jobName, Type jobType, string jobKeyname, string time)
        {
            sched = sf.GetScheduler().Result;              //工厂生成一个调度器 

            JobDetailImpl jobDetail = new JobDetailImpl();      //新建一个任务 
            jobDetail.Name = jobName;
            jobDetail.Group = JOB_GROUP_NAME;
            jobDetail.Key = new JobKey(jobKeyname); //JobKey.Create(jobkey);
            jobDetail.JobType = jobType;

            CronTriggerImpl trigger = new CronTriggerImpl(jobName, TRIGGER_GROUP_NAME);//新建一个触发器  
            trigger.CronExpressionString = time;   //Cron表达式
            sched.ScheduleJob(jobDetail, trigger); //将任务与触发器添加到调度器中 
            if (!sched.IsShutdown)
            {
                sched.Start();
            }
        }

        /**   
         * 从Scheduler 移除当前的Job,修改Trigger   
         *    
         * @param jobDetail   
         * @param time   
         * @throws SchedulerException   
         * @throws ParseException   
         */
        public static void ModifyJobTime(string jobName, Type jobType, string jobKeyname, string time, bool IsEdit = true)
        {
            sched = sf.GetScheduler().GetAwaiter().GetResult();
            //创建之前的trigger
            CronTriggerImpl trigger = new CronTriggerImpl(jobName, TRIGGER_GROUP_NAME);

            //创建之前的job
            JobDetailImpl jobDetail = new JobDetailImpl();      //新建一个任务 
            jobDetail.Name = jobName;
            jobDetail.Group = JOB_GROUP_NAME;
            jobDetail.Key = new JobKey(jobKeyname); //JobKey.Create(jobkey);
            jobDetail.JobType = jobType;

            // 移除当前进程的Job     
            sched.DeleteJob(jobDetail.Key);
            if (IsEdit)
            {
                // 修改Trigger     
                trigger.CronExpressionString = time;
                // 重新调度jobDetail       
                sched.ScheduleJob(jobDetail, trigger);
            }
        }
        #endregion
    }

将时间转为Cron

public class TimeToCron
    {

        /// <summary>
        /// 时间格式转换成Quartz任务调度器Cron表达式
        /// </summary>
        /// <param name="timeStr">时间值,支持yyyy-MM-dd HH:mm:ss | HH:mm</param>
        /// <returns></returns>
        public static string TimeToQuartzCron(string timeStr)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(timeStr))
                {
                    return "";
                }
                //日期
                string date = Convert.ToDateTime(timeStr).ToString("yyyy-MM-dd");
                DateTime dt = DateTime.Parse(date);
                //时间
                string time = Convert.ToDateTime(timeStr).ToString("HH:mm:ss");
                string error = "传入的时间值[" + timeStr + "]格式有误!";
                int ss = 0, mi = 0, hh = 0;
                if (time.Length < 5)
                {
                    throw new Exception(error);
                }
                if (time.Substring(2, 1) != ":")
                {
                    throw new Exception(error);
                }
                if (!int.TryParse(time.Substring(0, 2), out hh))
                {
                    throw new Exception(error);
                }
                if (!int.TryParse(time.Substring(3, 2), out mi))
                {
                    throw new Exception(error);
                }
                if (time.Length > 5)
                {
                    if (time.Substring(5, 1) != ":")
                    {
                        throw new Exception(error);
                    }
                    if (!int.TryParse(time.Substring(6), out ss))
                    {
                        throw new Exception(error);
                    }
                }
                if (ss > 59)
                {
                    throw new Exception(error);
                }
                if (mi > 59)
                {
                    throw new Exception(error);
                }
                if (hh > 23)
                {
                    throw new Exception(error);
                }
                string cronValue = ss + " " + mi + " " + hh + " " + dt.Day.ToString() + " " + dt.Month.ToString() + " ? " + dt.Year.ToString();
                return cronValue;
            }
            catch (Exception ea)
            {
                throw ea;
            }
        }
    }
上一篇下一篇

猜你喜欢

热点阅读