首页 > 其他分享 >08_Quartz.NET使用

08_Quartz.NET使用

时间:2024-05-09 14:23:53浏览次数:17  
标签:Task Console 08 await Quartz WriteLine async NET public

Quartz.NET 是一个用于调度任务和作业的开源框架,它允许开发人员创建简单或复杂的调度方案,例如定时执行任务,定时触发作业等。

创建调度器很简单需要三个对象:  IScheduler、IJob、ITrigger,直接上代码,使用可根据需求再扩展

using Quartz;
using Quartz.Impl;
using QuartzScheduler.Job;
using QuartzScheduler.Listener;

namespace QuartzScheduler
{
    /// <summary>
    /// 调度器
    /// </summary>
    public class MyScheduler
    {
        /// <summary>
        /// 创建调度器
        /// </summary>
        public async static Task SchedulerAction()
        {
            //IScheduler
            StdSchedulerFactory stdScheduler = new StdSchedulerFactory();
            IScheduler scheduler = await stdScheduler.GetScheduler();
            await scheduler.Start();

            //添加监听器
            scheduler.ListenerManager.AddJobListener(new JobListener());//Job监听器
            scheduler.ListenerManager.AddTriggerListener(new TriggerListener());//Trigger监听器
            scheduler.ListenerManager.AddSchedulerListener(new SchedulerListener());//Scheduler监听器

            //IJob
            IJobDetail jobDetail = JobBuilder.Create<QuartzJobDemo01>()
                .WithIdentity("JobName", "Group01")                                       //唯一标识
                .WithDescription("这里是描述......")                                      //信息描述
                .StoreDurably(true)                                                       //孤立存储
                .RequestRecovery(true)                                                    //请求恢复,指应用崩溃后再次启动,会重新执行该作业
                .Build();

            //IJob设置参数
            jobDetail.JobDataMap.Add("UserName1", "张三");
            jobDetail.JobDataMap.Add("Weight", 100);
            jobDetail.JobDataMap.Add("time", DateTime.Now);


            //ITrigger
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("TriggerName", "Group01")
                //.StartAt(new DateTimeOffset())                 //从某时间段开始执行
                //.StartNow()                                  //从现在开始

                //链式策略
                //.WithSimpleSchedule(p =>
                //{
                //    p.WithIntervalInSeconds(5)        //5秒执行一次,(WithIntervalInHours小时,WithIntervalInMinutes分钟)
                //    //.WithRepeatCount(3)             //执行3次
                //    .RepeatForever();                 //一直执行      

                //正则表达式策略
                .WithCronSchedule("0/5 * * * * ? ")    //每5秒执行一次:https://cron.ciding.cc/在线正则解析
                .Build();

            // ITrigger设置参数
            trigger.JobDataMap.Add("Age", 18);


            //添加调度
            await scheduler.ScheduleJob(jobDetail, trigger);


        }
    }
}

 

QuartzJobDemo01.cs

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzScheduler.Job
{
    /// <summary>
    /// 任务01
    /// </summary>
    [PersistJobDataAfterExecution]//执行后保留作业数据
    [DisallowConcurrentExecution]//确保上次执行完成后才能执行这次
    public class QuartzJobDemo01 : IJob
    {
        public QuartzJobDemo01()
        {
            Console.WriteLine("--QuartzJobDemo01被构造了-");
        }

        public async Task Execute(IJobExecutionContext context)
        {
            await Task.Factory.StartNew(() =>
            {
                string? username01= context.JobDetail.JobDataMap.GetString("UserName1"); 
                int? weight = context.JobDetail.JobDataMap.GetInt("Weight");
                string? time = context.JobDetail.JobDataMap.GetDateTime("time").ToString();
                int? age = context.Trigger.JobDataMap.GetInt("Age");
                Console.WriteLine("--------------------------------------");
                Console.WriteLine($"Hello,这是QuartzJobDemo01...........");
                Console.WriteLine($"传过来的参数UserName01:{username01}");
                Console.WriteLine($"传过来的参数Weight:{weight}");
                Console.WriteLine($"传过来的参数time:{time}");
                Console.WriteLine($"传过来的参数Age:{age}");

                context.JobDetail.JobDataMap.Put("Weight", weight + 1);//保留作业数据测试
                Console.WriteLine("--------------------------------------");
            });
        }
    }
}

 

JobListener.cs

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzScheduler.Listener
{
    /// <summary>
    /// Job监听器
    /// </summary>
    public class JobListener : IJobListener
    {
        public string Name => "JobListener的名称";

        /// <summary>
        /// 任务中断后执行
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine("任务中断后执行..........."));
        }

        /// <summary>
        /// 执行前触发
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine("执行前触发..........."));
        }

        /// <summary>
        /// 执行后会触发
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jobException"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task JobWasExecuted(IJobExecutionContext context, JobExecutionException? jobException, CancellationToken cancellationToken = default)
        {
            await Task.Run(() =>Console.WriteLine("执行后会触发..........."));
        }
    }
}

 

TriggerListener.cs

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzScheduler.Listener
{
    /// <summary>
    /// Trigger监听器
    /// </summary>
    public class TriggerListener : ITriggerListener
    {
        public string Name => "TriggerListener名称";

        /// <summary>
        /// 在JobListener触发完再触发
        /// </summary>
        /// <param name="trigger"></param>
        /// <param name="context"></param>
        /// <param name="triggerInstructionCode"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine("TriggerListener---->TriggerComplete,在JobListener触发完再触发..........."));
            Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("");
        }

        /// <summary>
        /// 在JobListener触发前触发
        /// </summary>
        /// <param name="trigger"></param>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async  Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine("TriggerListener---->TriggerFired,在JobListener触发前触发 ..........."));
        }

        public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine("TriggerListener---->TriggerMisfired ..........."));
        }

        /// <summary>
        /// 返回true取消执行,false继续执行
        /// </summary>
        /// <param name="trigger"></param>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            //返回true 只会执行TriggerFired方法
            return await Task.Run(() => {
                return false;
            });
        }
    }
}

 

SchedulerListener.cs

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzScheduler.Listener
{
    /// <summary>
    ///  Scheduler监听器   https://www.quartz-scheduler.net/documentation/quartz-3.x/tutorial/scheduler-listeners.html
    /// </summary>
    public class SchedulerListener : ISchedulerListener
    {
        /// <summary>
        /// Job被添加时
        /// </summary>
        /// <param name="jobDetail"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task JobAdded(IJobDetail jobDetail, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobAdded ******{jobDetail.Key.Name}"));
        }

        public async Task JobDeleted(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobDeleted ******{jobKey.Name}"));
        }

        public async Task JobInterrupted(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobInterrupted ******{jobKey.Name}"));
        }

        public async Task JobPaused(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobPaused ******{jobKey.Name}"));
        }

        public async Task JobResumed(JobKey jobKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobResumed ******{jobKey.Name}"));
        }

        public async Task JobScheduled(ITrigger trigger, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobScheduled ******{trigger.Key.Name}"));
        }

        public async Task JobsPaused(string jobGroup, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobsPaused ******{jobGroup}"));
        }

        public async Task JobsResumed(string jobGroup, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobsResumed ******{jobGroup}"));
        }

        public async Task JobUnscheduled(TriggerKey triggerKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** JobUnscheduled ******{triggerKey.Name}"));
        }

        public async Task SchedulerError(string msg, SchedulerException cause, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerError ******{msg}"));
        }

        public async Task SchedulerInStandbyMode(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerInStandbyMode ******"));
        }

        public async Task SchedulerShutdown(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerShutdown ******"));
        }

        public async Task SchedulerShuttingdown(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerShuttingdown ******"));
        }

        public async Task SchedulerStarted(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerStarted ******"));
        }

        public async Task SchedulerStarting(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulerStarting ******"));
        }

        public async Task SchedulingDataCleared(CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** SchedulingDataCleared ******"));
        }

        public async Task TriggerFinalized(ITrigger trigger, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** TriggerFinalized ******{trigger.Key.Name}"));
        }

        public async Task TriggerPaused(TriggerKey triggerKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** TriggerPaused ******{triggerKey.Name}"));
        }

        public async Task TriggerResumed(TriggerKey triggerKey, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** TriggerResumed ******{triggerKey.Name}"));
        }

        public async Task TriggersPaused(string? triggerGroup, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** TriggersPaused ******{triggerGroup}"));
        }

        public async Task TriggersResumed(string? triggerGroup, CancellationToken cancellationToken = default)
        {
            await Task.Run(() => Console.WriteLine($"****** TriggersResumed ******{triggerGroup}"));
        }
    }
}

 

调用

internal class Program
    {
        static void Main(string[] args)
        {
            MyScheduler.SchedulerAction().GetAwaiter().GetResult();

            Console.Read();
        }
    }

 

标签:Task,Console,08,await,Quartz,WriteLine,async,NET,public
From: https://www.cnblogs.com/MingQiu/p/18182039

相关文章

  • 使用.NET查询日出日落时间
    在WPF中,通过资源文件实现主题切换是个常见的功能,有不少文章介绍了如何实现手动切换主题。那如何实现自动切换主题呢?通常有两种机制:一是跟随系统明暗主题切换,二是像手机操作系统那样根据日出日落时间自动切换。本文将以终为始,采用倒推法一步步介绍如何使用.NET免费获取日出日落时间......
  • dotnet 9 WPF 支持 Style 的 Setter 填充内容时可忽略 Value 标签
    本文记录WPF在dotnet9的一项XAML编写语法改进点,此改进点用于解决编写Style的Setter进行给Value赋值时,不能将Value当成默认内容,需要多写Value标签的问题。通过此改进点可减少两行XAML代码在原先的WPF版本里面,对Style的Setter填充复杂的对象内容时,大概的......
  • C#.Net筑基-基础知识
    01、C#基础概念1.1、C#简介C#(读作CSharp)是由微软公司开发的一种面向对象、类型安全、高效且简单的编程语言,最初于2000年发布,并随后成为.NET框架的一部分。所以学习C#语言的同时,也是需要同步学习.NET框架的,不过要要注意C#与.NET的对应版本。C#语言和Java类似,是一门简单......
  • .NET有哪些好用的定时任务调度框架
    前言定时任务调度的相关业务在日常工作开发中是一个十分常见的需求,经常有小伙伴们在技术群提问:有什么好用的定时任务调度框架推荐的?今天大姚给大家分享5个.NET开源、简单、易用、免费的任务调度框架,帮助大家在做定时任务调度框架技术选型的时候有一个参考。以下开源任务调度收......
  • 232自由口转Profinet网关接基恩士扫码枪与PLC通讯案例
     232自由口转Profinet网关(XD-PNR100/300)是一款作用于将232自由口转换为Profinet协议,实现不同网络之间的无缝通信和数据交换。232自由口转Profinet网关具有极高的灵活性和可靠性,为工业控制系统提供了强大的支持。通过将自由口信号转换为Profinet协议,可以轻松实现不同设备之间的......
  • 2024-05-08 js 常见案例
    1.表单验证functionvalidateForm(){varname=document.forms["myForm"]["name"].value;if(name==""){alert("Namemustbefilledout");returnfalse;}//更多的验证.........
  • 盘点10个.Net比较流行的开源的ORM框架
    https://gitee.com/BookerLiu/GeekDesk编程乐趣2022-09-10对于我们而言选择ORM框架的目的,其实都是为了让我们的程序更好的操作数据库,提高开发编程效率和程序的维护拓展性。所以我们选择ORM需要从项目实际业务出发,选择最合适自己团队的框架。下面推荐10个主流比较流行的ORM框架,都......
  • Kubernetes——K8s基础指令
    1、查看类命令#获取节点和服务版本信息kubectlgetnodes#获取节点和服务版本信息,并查看附加信息kubectlgetnodes-owide#获取pod信息,默认是default名称空间kubectlgetpod#获取pod信息,默认是default名称空间,并查看附加信息如:pod的IP及在哪个节点运行kubectlg......
  • 5个.Net版本 Redis 客户端开源库
    Redis作为一个高性能(NOSQL)的key-value数据库,在实际项目开发中运用非常广泛,也适用于很多业务场景。下面介绍5个.Net版本Redis客户端开源库,方便开发和提升效率。1、StackExchange.Redis简介:由StackExchange团队开发。它提供了丰富的功能和选项,如连接池、管道、事务、发布/订阅......
  • 20240508打卡
    第十一周第一天第二天第三天第四天第五天第六天第七天所花时间3h5h2h代码量(行)276122371博客量(篇)111知识点了解设计后台系统界面和每日委托第一阶段验收,理清项目优化方向接口测试......