Fork me on GitHub

Quartz.net任务调度

一、Quartz.net简介

  Quartz.net是一个开源的任务调度框架,很多定时任务、调度任务都可以用这个框架,如定时日志等。

二、Quartz.net用途

  • 定时给女朋友发送消息
  • 女朋友生日的时候定时提醒
  • 购物定时打折任务

三、Quartz.net实例

  • 安装

     Quartz.net的安装通过 NuGet包管理 安装,打开 NuGet包管理,搜索Quartz.net,点击安装。

 

 

 也可以在nuget控制台输入:Install-Package Quartz实现安装。

  • 实现

继承IJob接口,实现Execute方法,以下是一个简单的定时写日志的实现

public class WriteLogJob : IJob
    {
        /// <summary>
        /// 实现接口
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Execute(IJobExecutionContext context)
        {
            Task task = null;
            try
            {
                string fileName = "quartzLog.txt";
                using (StreamWriter writer = new StreamWriter(fileName, true))
                {
                    task = writer.WriteAsync($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\r\n");
                }
            }
            catch (Exception)
            {

            }

            return task;
        }
    }

 

  • 配置和自定义管理IScheduler
 public class QuartzHelper
    {
        static readonly IScheduler scheduler;
        static QuartzHelper()
        {
            try
            {
                var properties = new NameValueCollection();
                //1.设置线程池
                properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
                //2.设置线程池最大数量
                properties["quartz.threadPool.threadCount"] = "5";
                //3.设置作业中每个线程的优先级
                properties["quartz.threadPool.threadPriority"] = System.Threading.ThreadPriority.Normal.ToString();
                //4.远程输出配置
                properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
                properties["quartz.scheduler.exporter.port"] = "5555";
                properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
                properties["quartz.scheduler.exporter.channelType"] = "tcp";



                //properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
                ////设置线程池的最大线程数量
                //properties["quartz.threadPool.threadCount"] = "5";
                ////设置作业中每个线程的优先级
                //properties["quartz.threadPool.threadPriority"] = System.Threading.ThreadPriority.Normal.ToString();

                //// 远程输出配置
                //properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
                //properties["quartz.scheduler.exporter.port"] = "555";  //配置端口号
                //properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
                //properties["quartz.scheduler.exporter.channelType"] = "tcp"; //协议类型


                //5.创建一个工程
                var schedulerFactory = new StdSchedulerFactory(properties);
                //6.启动
                scheduler = schedulerFactory.GetScheduler().Result;
                //7.      一、开启调度
                scheduler.Start();

            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 时间间隔执行任务
        /// </summary>
        /// <typeparam name="T">任务类,必须实现IJob接口</typeparam>
        /// <param name="seconds">时间间隔(单位:秒)</param>
        public static async Task<bool> ExecuteInterval<T>(int seconds) where T : IJob
        {
            try
            {
                //2、创建工作任务
                IJobDetail job = JobBuilder.Create<T>().Build();
                // 3、创建触发器
                ITrigger trigger = TriggerBuilder.Create().StartNow().
                    WithSimpleSchedule(x => x.WithIntervalInSeconds(seconds)
                                        //x.WithIntervalInMinutes(1)
                                        .RepeatForever())
                                        .Build();
                //4、将任务加入到任务池
                await scheduler.ScheduleJob(job, trigger);
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }

        /// <summary>
        /// 指定时间执行任务
        /// </summary>
        /// <typeparam name="T">任务类,必须实现IJob接口</typeparam>
        /// <param name="cronExpression">cron表达式,即指定时间点的表达式</param>
        public static async Task<bool> ExecuteByCron<T>(string cronExpression) where T : IJob
        {
            try
            {
                //2、创建工作任务
                IJobDetail job = JobBuilder.Create<T>().Build();
                //3、创建触发器
                ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
   .StartNow()
   .WithCronSchedule(cronExpression)
   .Build();
                //4、将任务加入到任务池
                await scheduler.ScheduleJob(job, trigger);
                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }
    }
  • 采用时间表达式来定时执行
  string cronExpression = "0/5 0/1 11 * * ? ";  //=>11点没五秒执行一次调度任务
          
   QuartzHelper.ExecuteByCron<WriteLogJob>(cronExpression).Wait();
  • 定时执行
QuartzHelper.ExecuteInterval<WriteLogJob>(2).Wait();

以上便是Quartz简单使用方法。

 

posted @ 2019-10-16 12:57  黄高林  阅读(423)  评论(0编辑  收藏  举报