首页 > 其他分享 >Quartz.Net间隔N周/日/年定时触发器写法总结

Quartz.Net间隔N周/日/年定时触发器写法总结

时间:2023-05-09 11:44:23浏览次数:37  
标签:触发器 Quartz sched Exception new Net pStrJobName QuartzManager

由于近日在定时器中对特殊的规则(既不能通过表达式直接体现的)的用法初步汇总:

本次使用的Quartz.Net的版本号:2.6

1.触发器测试验证

  public class TestQuartz
    {
        /// <summary>
        /// 间隔N周定时触发器写法测试
        /// </summary>
        public static void TestWeeklyIntervalGetFireTimeAfter()
        {
            DateTimeOffset startCalendar = DateBuilder.DateOf(1, 10, 0, 1, 1, 2023);

            var yearlyTrigger = new CalendarIntervalTriggerImpl
            {
                StartTimeUtc = startCalendar,
                RepeatIntervalUnit = IntervalUnit.Week,
                RepeatInterval = 2,
                PreserveHourOfDayAcrossDaylightSavings = true
            };

            DateTimeOffset targetCalendar = startCalendar.AddDays(7 * 2); // jump 24 weeks (4 intervals)

            IList<DateTimeOffset> fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 24);
            DateTimeOffset fifthTime = fireTimes[1]; // get the fifth fire time

            Assert.AreEqual(targetCalendar, fifthTime, "Week increment result not as expected.");
        }
        /// <summary>
        /// 间隔N天定时触发器写法测试
        /// </summary>
        public static void TestDayIntervalGetFireTimeAfter()
        {
            DateTimeOffset startCalendar = DateBuilder.DateOf(1, 10, 0, 1, 1, 2023);

            var yearlyTrigger = new CalendarIntervalTriggerImpl
            {
                StartTimeUtc = startCalendar,
                RepeatIntervalUnit = IntervalUnit.Day,
                RepeatInterval = 1,
                PreserveHourOfDayAcrossDaylightSavings = true
            };

            DateTimeOffset targetCalendar = startCalendar.AddDays(1); // jump 24 weeks (4 intervals)

            IList<DateTimeOffset> fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 365);
            DateTimeOffset fifthTime = fireTimes[1]; // get the fifth fire time

            Assert.AreEqual(targetCalendar, fifthTime, "Week increment result not as expected.");
        }
        /// <summary>
        /// 间隔N月定时触发器写法测试
        /// </summary>
        public static void TestMonthIntervalGetFireTimeAfter()
        {
            DateTimeOffset startCalendar = DateBuilder.DateOf(23, 20, 0, 1, 1, 2023);

            var yearlyTrigger = new CalendarIntervalTriggerImpl
            {
                StartTimeUtc = startCalendar,
                RepeatIntervalUnit = IntervalUnit.Month,
                RepeatInterval = 1,
                PreserveHourOfDayAcrossDaylightSavings = true
            };

            DateTimeOffset targetCalendar = startCalendar.AddMonths(1); // jump 24 weeks (4 intervals)

            IList<DateTimeOffset> fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 12);
            DateTimeOffset fifthTime = fireTimes[1]; // get the fifth fire time

            Assert.AreEqual(targetCalendar, fifthTime, "Week increment result not as expected.");
        }
    }

注册工具实现

    /// <summary>
    /// 定时器管理工具类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class QuartzManager<T> where T : class, IJob
    {
        #region 变量
        /// <summary>
        /// scheduler工厂
        /// </summary>
        private static ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
        /// <summary>
        /// Job群组名
        /// </summary>
        private static String JOB_GROUP_NAME = "JOBGROUP_NAME";
        /// <summary>
        /// 触发器群组名
        /// </summary>
        private static String TRIGGER_GROUP_NAME = "TRIGGERGROUP_NAME";
        private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        #endregion

        #region 添加,删除,修改Job方法
        /// <summary>
        /// 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
        /// </summary>
        /// <param name="pStrJobName">任务名</param>
        /// <param name="pStrCronExpress">触发器表达式</param>
        public static void addJob(string pStrJobName, string pStrCronExpress, IDictionary<string, object> pDictionary)
        {
            try
            {
                IScheduler sched = schedulerFactory.GetScheduler();
                // 创建任务
                IJobDetail job = JobBuilder.Create<T>()
                    .WithIdentity(pStrJobName, JOB_GROUP_NAME)
                    .Build();

                // 创建触发器
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity(pStrJobName, TRIGGER_GROUP_NAME)
                    .WithCronSchedule(pStrCronExpress)
                    .Build();

                //给任务传参数
                foreach (KeyValuePair<string, object> kvp in pDictionary)
                {
                    job.JobDataMap.Put(kvp.Key, kvp.Value);
                }

                sched.ScheduleJob(job, trigger);
                logger.Info("加载了服务:" + pStrJobName);
            }
            catch (Exception e)
            {
                logger.Info("加载异常:" + e.Message);
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 添加一个定时任务,使用自定义规则
        /// </summary>
        /// <param name="pStrJobName">任务名</param>
        /// <param name="doDailyTime">自定义执行情况</param>
        /// <param name="doCalendar">自定义执行情况</param>
        /// <param name="startTimeUtc">触发器执行起点时间</param>
        public static void addJob(string pStrJobName, Action<DailyTimeIntervalScheduleBuilder> doDailyTime
            , Action<CalendarIntervalScheduleBuilder> doCalendar,
          DateTimeOffset startTimeUtc,
            IDictionary<string, object> pDictionary)
        {
            try
            {
                IScheduler sched = schedulerFactory.GetScheduler();
                // 创建任务
                IJobDetail job = JobBuilder.Create<T>()
                    .WithIdentity(pStrJobName, JOB_GROUP_NAME)
                    .Build();

                // 创建触发器
                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity(pStrJobName, TRIGGER_GROUP_NAME)
                    .WithCalendarIntervalSchedule(d =>
                    {
                        if (doCalendar != null)
                        { doCalendar(d); }
                    })
                    .WithDailyTimeIntervalSchedule(d =>
                    {
                        if (doCalendar != null)
                        { doDailyTime(d); }
                    })
                    .StartAt(startTimeUtc)
                    .Build();

                //给任务传参数
                foreach (KeyValuePair<string, object> kvp in pDictionary)
                {
                    job.JobDataMap.Put(kvp.Key, kvp.Value);
                }

                sched.ScheduleJob(job, trigger);
                logger.Info("加载了服务:" + pStrJobName);
            }
            catch (Exception e)
            {
                logger.Info("加载异常:" + e.Message);
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 定时器高级注册应用
        /// </summary>
        /// <param name="pStrJobName">任务名</param>
        /// <param name="myTrigger">自定义</param>
        /// <param name="pDictionary">自定义参数</param>
        public static void addJob<TiggerImpl>(string pStrJobName, Func<TiggerImpl, ITrigger> myTrigger,
            IDictionary<string, object> pDictionary)
            where TiggerImpl : CalendarIntervalTriggerImpl
        {
            try
            {
                IScheduler sched = schedulerFactory.GetScheduler();
                // 创建任务
                IJobDetail job = JobBuilder.Create<T>()
                    .WithIdentity(pStrJobName, JOB_GROUP_NAME)
                    .Build();

                // 创建触发器
                ITrigger trigger = myTrigger(Activator.CreateInstance<TiggerImpl>());

                //给任务传参数
                foreach (KeyValuePair<string, object> kvp in pDictionary)
                {
                    job.JobDataMap.Put(kvp.Key, kvp.Value);
                }

                sched.ScheduleJob(job, trigger);
                logger.Info("加载了服务:" + pStrJobName);
            }
            catch (Exception e)
            {
                logger.Info("加载异常:" + e.Message);
                throw new Exception(e.Message);
            }
        }



        /// <summary>
        /// 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
        /// </summary>
        /// <param name="pStrJobName">任务名称</param>
        public static void RemoveJob(string pStrJobName)
        {
            try
            {
                IScheduler sched = schedulerFactory.GetScheduler();
                JobKey jobKey = new JobKey(pStrJobName);
                TriggerKey triggerKey = new TriggerKey(pStrJobName, TRIGGER_GROUP_NAME);
                sched.PauseTrigger(triggerKey);// 停止触发器
                sched.UnscheduleJob(triggerKey);// 移除触发器
                sched.DeleteJob(jobKey);// 删除任务
                logger.Info("卸载了服务:" + pStrJobName);
            }
            catch (Exception e)
            {
                logger.Info("卸载异常:" + e.Message);
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
        /// </summary>
        /// <param name="pStrJobName">任务名</param>
        /// <param name="pStrCronExpress">触发器表达式</param>
        public static void ModifyJobTime(string pStrJobName, string pStrCronExpress, IDictionary<string, object> pDictionary)
        {
            try
            {
                IScheduler sched = schedulerFactory.GetScheduler();
                TriggerKey triggerKey = new TriggerKey(pStrJobName, TRIGGER_GROUP_NAME);
                ICronTrigger trigger = (ICronTrigger)sched.GetTrigger(triggerKey);
                if (trigger == null)
                {
                    return;
                }
                RemoveJob(pStrJobName);
                addJob(pStrJobName, pStrCronExpress, pDictionary);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
        #endregion

        #region 启动,关闭Job
        /// <summary>
        /// 启动所有定时任务
        /// </summary>
        public static void startJobs()
        {
            try
            {
                IScheduler sched = schedulerFactory.GetScheduler();
                sched.Start();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        /// <summary>
        /// 关闭所有定时任务
        /// </summary>
        public static void ShutdownJobs()
        {
            try
            {
                IScheduler sched = schedulerFactory.GetScheduler();
                if (!sched.IsShutdown)
                {
                    sched.Shutdown();
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
        #endregion

    }

定制注册示例

 public partial class PubDataService : ServiceBase
    {
        public PubDataService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                LogHelper.WriteLog("服务开始启动!");

                //定时生成病害检查自动任务数据连接服务(0.5时/次)
                QuartzManager<StcDiseaseManagerTask>.addJob("StcDiseaseManagerTask", ConfigHelper.GetAppSetting("cornExpress01"), new Dictionary<string, object>());
                QuartzManager<StcDiseaseManagerTask>.startJobs();//定时生成二次注浆区段自动任务数据连接服务(1月/次)
                #region 验证已通过
                QuartzManager<KeySectionSecondGroutSectionTask>.addJob<CalendarIntervalTriggerImpl>("KeySectionSecondGroutSectionTask",
                    d =>
                    {
                        d.StartTimeUtc = DateBuilder.DateOf(23, 20, 0, 1, 1, 2023);
                        d.RepeatIntervalUnit = IntervalUnit.Month;
                        d.RepeatInterval = 1;
                        d.PreserveHourOfDayAcrossDaylightSavings = true;
                        return d;
                    },
                    new Dictionary<string, object>());
                #endregion
                QuartzManager<KeySectionSecondGroutSectionTask>.startJobs();

                //定时生成技术状况2级及以上影响区段自动任务数据连接服务(1月/次)
                QuartzManager<KeySectionTechnicalValueSectionTask>.addJob("KeySectionTechnicalValueSectionTask", ConfigHelper.GetAppSetting("cornExpress04"), new Dictionary<string, object>());
                QuartzManager<KeySectionTechnicalValueSectionTask>.startJobs();

                //定时生成技术状况评定计算连接服务-单环评定(1日/次)
                QuartzManager<TecConditionSingleDataTask>.addJob("TecConditionSingleDataTask", ConfigHelper.GetAppSetting("cornExpress05"), new Dictionary<string, object>());
                QuartzManager<TecConditionSingleDataTask>.startJobs();

                //定时生成技术状况评定计算连接服务-区段评定(2周/次)
                #region 验证已通过
                QuartzManager<TecConditionStcSectionTask>.addJob<CalendarIntervalTriggerImpl>("TecConditionStcSectionTask",
                    d =>
                    {
                        d.StartTimeUtc = DateBuilder.DateOf(23, 30, 0, 1, 1, 2023);
                        d.RepeatIntervalUnit = IntervalUnit.Week;
                        d.RepeatInterval = 2;
                        d.PreserveHourOfDayAcrossDaylightSavings = true;
                        return d;
                    },
                    new Dictionary<string, object>());
                #endregion
                QuartzManager<TecConditionStcSectionTask>.startJobs();


                LogHelper.WriteLog("服务启动成功!");
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("服务启动失败," + ex.Message, ex);
            }
        }
        protected override void OnStop()
        {
            LogHelper.WriteLog("服务开始关闭!");
            QuartzManager<StcDiseaseManagerTask>.ShutdownJobs();
            QuartzManager<StcDiseaseManagerTask>.RemoveJob("StcDiseaseManagerTask");

            QuartzManager<ElectroManagerTask>.ShutdownJobs();
            QuartzManager<ElectroManagerTask>.RemoveJob("ElectroManagerTask");

            QuartzManager<KeySectionSecondGroutSectionTask>.ShutdownJobs();
            QuartzManager<KeySectionSecondGroutSectionTask>.RemoveJob("KeySectionSecondGroutSectionTask");

            QuartzManager<KeySectionTechnicalValueSectionTask>.ShutdownJobs();
            QuartzManager<KeySectionTechnicalValueSectionTask>.RemoveJob("KeySectionTechnicalValueSectionTask");

            QuartzManager<TecConditionSingleDataTask>.ShutdownJobs();
            QuartzManager<TecConditionSingleDataTask>.RemoveJob("TecConditionSingleDataTask");

            LogHelper.WriteLog("服务关闭成功!");
        }
    }

 

标签:触发器,Quartz,sched,Exception,new,Net,pStrJobName,QuartzManager
From: https://www.cnblogs.com/oumi/p/17384442.html

相关文章

  • Java 定时任务quartz
    Java定时任务quartz1.java自带java.util.Timer实现定时任务2.使用线程池(ScheduledThreadPool-java.util.concurrent.ScheduledExecutorService)实现定时任务3.使用注解@Scheduled实现定时任务4.使用Quartz定时任务调度器4.1Quartz特点4.2核心概念4.3常用对象4.4实例......
  • U-net结构学习笔记
    UNet++作者在知乎上进行了解读,里面还有视频的讲解,深入人心.里面有一句话令我印象深刻,我总结下:很多论文给出了他们建议的网络结构,其中包括非常多的细节,比如用什么卷积,用几层,怎么降采样,学习率多少,优化器用什么,这些都是比较直观的参数,其实这些在论文中给出参数并不见得是最好的,......
  • SKNet 200epoch lolv1 分别使用压缩和不压缩
    SKNet在lolv1数据集epoch=200:psnr=22.92SSIM=0.9033/home/mmsys/anaconda3/envs/SFNet/bin/python3.8/media/mmsys/6f1091c9-4ed8-4a10-a03d-2acef144d2e1/SXY/restoration/SFNet_main_old/main.py[WCopy.cpp:219]Warning:Castingcomplexvaluestorealdiscard......
  • .NET周报 【5月第1期 2023-05-06】
    国内文章聊一聊Valgrind监视非托管内存泄露和崩溃https://www.cnblogs.com/huangxincheng/p/17374315.html、只要是程序总会出现各种莫名其妙的问题,比如:非托管内存泄露,程序崩溃,在Windows平台上一般用微软自家的官方工具AppVerifier就可以洞察,那问题出在Linux上怎么办......
  • 高维数据惩罚回归方法:主成分回归PCR、岭回归、lasso、弹性网络elastic net分析基因数
    全文链接:http://tecdat.cn/?p=23378最近我们被客户要求撰写关于高维数据惩罚回归方法的研究报告,包括一些图形和统计输出。在本文中,我们将使用基因表达数据。这个数据集包含120个样本的200个基因的基因表达数据。这些数据来源于哺乳动物眼组织样本的微阵列实验1介绍在本文中,我......
  • m车载自组织网络(Vehicular Ad-hoc Network,VANET)通信系统的matlab仿真
     1.算法仿真效果 matlab2022a仿真结果如下:         2.算法涉及理论知识概要          这里根据那个fluiddynamicmodel和stochasticmodel模型,这里使用一种如下的车辆移动模型,能够反映出车辆移动的随机性和连续性。       ......
  • 获取.Net程序集的PublicKeyToken
    C:\ProgramData\Microsoft\Windows\StartMenu\Programs\VisualStudio2022\VisualStudioToolsSN-TC:\Users\97627\.nuget\packages\system.data.sqlclient\4.8.5\ref\netcoreapp2.1\System.Data.SqlClient.dll#SN-TYou.dll   ......
  • .Net开发的音频分离桌面应用,可用于提取背景音乐
    背景音乐对于视频来说是非常重要的,制作视频的人来说,听到一些符合自己视频的背景音乐,又找不到背景音乐的源音乐,这时候就需要有软件帮助提取背景音乐了。项目简介这是基于C#开发的UI界面,支持中文等多国语言、支持分离人声背景音乐的桌面软件,可用于提取背景音乐。底层核心是基于Py......
  • 搭建 Kubernetes 集群
    简介Kubernetes是一个开源系统,用于容器化应用的自动部署、扩缩和管理。它将构成应用的容器按逻辑单位进行分组以便于管理和发现。搭建环境:CentOSv7.6.1810docker-ce-versionv23.0.5kubernetes-versionv1.23.6本次使用2台服务器进行搭建,运行下面命令写入/etc/hosts文件(......
  • Cisco 思科路由交换-开启telnet
    Router>enable   进入特权模式Router#configterminal  进入全局模式Router(config)#hostnamer1  路由器修改名字r1(config)#noipdomain-lookup   取消dns查询r1(config)#linevty04          开启telnetr1(config-line)#password123  设置密码 ......