• 【c#】Quartz开源任务调度框架学习及练习Demo


    Quartz开源任务调度框架学习及练习Demo

    1、定义、作用

    2、原理

    3、使用步骤

    4、使用场景

    5、Demo代码参考示例

    6、注意事项

    7、一些Trigger属性说明

    1、定义、作用

    Quartz是一个开源的任务调度框架,作用是支持开发人员可以定时处理业务,比如定时发布邮件等定时操作。

    2、原理

    Quartz大致可以分为四部分,但是按功能分的话三部分就可以:schedule(调度器是schedule的一个调度单元)、job(任务)、Trigger(触发器)

    scedule功能:统筹任务调度,
    JOB:实现具体的任务
    Trigger:设置触发任务的条件,比如定时

    在这里插入图片描述

    3、使用步骤

    1、在项目NUGET包管理器中安装并添加Quartz引用
    2、创建JOB任务类,继承并实现Ijob接口,在接口Execute方法中写具体任务
    3、创建Schedule调度器
    4、创建作业JOB,设置作业名称,将作业注册到调度器中
    5、创建触发器trigger对象,设置触发器名称,触发时机,将触发器注册到调度器中
    6、启动调度器,开始作业
    7、调度器根据触发器设置,决定何时执行作业
    8、执行作业execute方法,执行具体作业逻辑
    9、调度器根据触发器设置,决定下一次执行作业时间
    10、重复执行8、9直到结束

    4、使用场景

    执行定时任务

    5、Demo代码参考示例

    JOB任务类:

    using Quartz;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace DesignTimerService
    {
        public class TestJob : IJob
        {
            string content = null;
            public async Task Execute(IJobExecutionContext context)
            {
                await Task.Run(() =>
                {
                	//这里写任务的具体业务逻辑
                    content = "现在是北京时间:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
    
                    WriteLog();
                });
    
    
            }
    
            public string WriteLog()
            {
                string path = @"C:\Users\KK\Desktop\log.txt";
               
                //
                if (!File.Exists(path))
                {
                    FileStream fs = File.Create(path);
                    fs.Close();
    
                }
                else
                {
                    StreamWriter writer = new StreamWriter(path, true, Encoding.Default);
                    writer.WriteLine(content);
                    writer.Flush();
                    writer.Close();
                    
                }
                return content;
            }
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    任务调度类:

    using DesignTimerService;
    using Quartz;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace JOB1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                //创建调度单元
                Task<IScheduler> tsk = Quartz.Impl.StdSchedulerFactory.GetDefaultScheduler();
                IScheduler scheduler = tsk.Result;
                //创建具体的作业,具体的job需要单独在一个执行文件中执行
                IJobDetail Job = JobBuilder.Create<TestJob>().WithIdentity("奇偶比JOB1").Build();
                //IJobDetail Job2 = JobBuilder.Create().WithIdentity("奇偶比JOB2").Build();
                //创建并配置一个触发器
                ITrigger _ctroTrigger = TriggerBuilder.Create().WithIdentity("定时奇偶比1").StartNow().Build() as ITrigger;
                //将job和trigger加入到作业调度中
                scheduler.ScheduleJob(Job, _ctroTrigger);
                //开启调度
                scheduler.Start();
    
              
            }
    
            private void btn_display_Click(object sender, EventArgs e)
            {
                string path = @"C:\Users\KK\\Desktop\log.xls";
    
                if (!File.Exists(path))
                {
                    string path1 = @"C:\Users\KK\\Desktop\log.txt";
                    StreamReader reader = new StreamReader(path1);
                    string content = reader.ReadToEnd();
                    tb_content.Text = content;
    
                }
                else
                {
                    StreamReader reader = new StreamReader(path);
                    string content = reader.ReadToEnd();
                    tb_content.Text = content;
                }
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62

    6、最终效果

    在这里插入图片描述

    7、一些Trigger属性说明

    1.WithSimpleSchedule: 指定从某一个时间开始,以一定的时间间隔(单位是毫秒)执行的任务。

    .WithSimpleSchedule(t => {
          t.RepeatForever();//重复次数不限
          //上下两者取其一
          t.WithRepeatCount(5);//设置重复次数,例如5次
          t.WithIntervalInHours(1);//设置执行间隔
          //上下两者取其一
          t.WithInterval(new TimeSpan(1, 2, 10));//设置重复间隔,用具体的小时,分钟,秒
     })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.WithCalendarIntervalSchedule:
    和WithSimpleSchedule类似,不同的是.SimpleSchedule指定的重复间隔只有(时,分,秒)而CalendarIntervalSchedule可以时(年,月,周,天,时,分,秒)

    .WithCalendarIntervalSchedule(t => {
          t.WithIntervalInDays(1);//间隔以天为单位
          t.WithIntervalInWeeks(1);//间隔以周为单位
          t.WithIntervalInMonths(1);//间隔以月为单位
          t.WithIntervalInYears(1);//间隔以年为单位
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3.WithDailyTimeIntervalSchedule: 指定每天的某个时间段内,以一定的时间间隔执行任务。并且它可以支持指定星期

    .WithDailyTimeIntervalSchedule(t => {
          t.OnEveryDay();//每天执行
          t.OnDaysOfTheWeek(DayOfWeek.Monday,DayOfWeek.Saturday);//每周的星期几执行
          t.OnMondayThroughFriday();//设置工作日执行(周一至周五)
          t.OnSaturdayAndSunday();//设置周末执行
          t.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0,30));//设置执行的开始时间
          //只设置开始时间,会在开始以后一直执行
          t.EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(1, 0));//设置停止执行的时间
          //二者表示,开某个时间段执行
          t.WithIntervalInHours(2);//设置重复间隔(更据方法不同可是时,分,秒)
          t.WithRepeatCount(10);//设置总共执行次数
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    4.StartNow()和.StartAt(new DateTimeOffset(new DateTime(2018,1,10))):

    StartNow:表示启动后立即执行一次.
    StartAt:表示启动后在指定日期或时间开始执行
    
    • 1
    • 2

    5.WithCronTrigger:

    以表达的形式定义触发条件
    
    • 1
  • 相关阅读:
    AtCoder Beginner Contest 264 G.String Fair(最短路/暴力dp 补写法)
    Linux Shell脚本练习(一)
    Nexus【应用 01】上传jar包到私有Maven仓库的两种方法:手动 Upload 和 mvn deploy 命令(配置+操作流程)
    54. 螺旋矩阵 & 59. 螺旋矩阵 II ●●
    手机桌面待办事项APP推荐
    Linux c编程之TCP通信
    二维数组根据某个字段进行分组
    驱动上下游高效协同,跨境B2B电商平台如何释放LED产业供应链核心价值
    使用4090显卡部署 Qwen-14B-Chat-Int4
    振兴农村循环经济 和数链串起农业“生态链”
  • 原文地址:https://blog.csdn.net/KJJfighting/article/details/133941783