|
Quartz.NET 是一个强大的开源作业调度库,提供了许多高级功能。以下是 Quartz.NET 的常用高级功能:
- Cron 表达式触发器: 使用 Cron 表达式定义灵活的调度规则,实现复杂的时间调度策略。
- 作业依赖性: 允许定义作业之间的依赖关系,确保它们按照特定的顺序执行。
- 作业执行中的数据传递: 在调度作业时,可以传递参数和数据,使得作业能够根据需要获取执行时的上下文信息。
- 全局作业监听器: 添加全局监听器,监听作业的执行生命周期事件,例如作业执行前、执行后等。
- 全局触发器监听器: 添加全局监听器,监听触发器的生命周期事件,例如触发器触发、触发器完成等。
- 自定义日历: 可以实现自定义的日历逻辑,例如排除特定日期或时间段,以满足业务需求。
- 集群模式: 允许将 Quartz.NET 实例配置为集群,实现分布式作业调度,确保高可用性和负载均衡。
- 持久性作业: Quartz.NET 提供了作业的持久性支持,可以将作业和触发器存储在数据库中,保证作业不会丢失。
- 作业状态记录: Quartz.NET 能够记录作业的执行状态,包括成功、失败、被否决等,方便监控和故障排查。
- 并行执行: 允许多个作业同时执行,提高系统的并发性能。
这些功能使得 Quartz.NET 成为一个灵活且功能丰富的作业调度框架,适用于各种复杂的调度需求。
以下是 Quartz.NET 的高级功能示例,包含中文注释:
1.Cron 表达式触发器
- using Quartz;
- using Quartz.Impl;
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- // 创建调度器工厂
- ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
- // 获取调度器实例
- IScheduler scheduler = schedulerFactory.GetScheduler().Result;
- // 创建作业
- IJobDetail job = JobBuilder.Create<NetworkStatusCheckJob>()
- .WithIdentity("networkStatusCheckJob", "group1")
- .Build();
- // 创建触发器,使用 Cron 表达式,每天10:30触发一次
- ITrigger trigger = TriggerBuilder.Create()
- .WithIdentity("networkStatusCheckTrigger", "group1")
- .StartNow()
- .WithCronSchedule("0 30 10 ? * *")
- .Build();
- // 将作业和触发器添加到调度器
- scheduler.ScheduleJob(job, trigger).Wait();
- // 启动调度器
- scheduler.Start().Wait();
- Console.WriteLine("Quartz.NET 已启动,按任意键退出...");
- Console.ReadKey();
- // 关闭调度器
- scheduler.Shutdown().Wait();
- }
- catch (SchedulerException se)
- {
- Console.WriteLine(se);
- }
- }
- }
复制代码 2.作业间的依赖性
- using Quartz;
- using Quartz.Impl;
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- // 创建调度器工厂
- ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
- // 获取调度器实例
- IScheduler scheduler = schedulerFactory.GetScheduler().Result;
- // 创建作业1
- IJobDetail job1 = JobBuilder.Create<Job1>()
- .WithIdentity("job1", "group1")
- .Build();
- // 创建作业2
- IJobDetail job2 = JobBuilder.Create<Job2>()
- .WithIdentity("job2", "group1")
- .Build();
- // 创建触发器1
- ITrigger trigger1 = TriggerBuilder.Create()
- .WithIdentity("trigger1", "group1")
- .StartNow()
- .Build();
- // 创建触发器2,设置在触发器1后执行
- ITrigger trigger2 = TriggerBuilder.Create()
- .WithIdentity("trigger2", "group1")
- .StartNow()
- .Build();
- // 将作业和触发器添加到调度器
- scheduler.ScheduleJob(job1, trigger1).Wait();
- scheduler.ScheduleJob(job2, trigger2.ForJob(job1).Build()).Wait();
- // 启动调度器
- scheduler.Start().Wait();
- Console.WriteLine("Quartz.NET 已启动,按任意键退出...");
- Console.ReadKey();
- // 关闭调度器
- scheduler.Shutdown().Wait();
- }
- catch (SchedulerException se)
- {
- Console.WriteLine(se);
- }
- }
- }
- public class Job1 : IJob
- {
- public void Execute(IJobExecutionContext context)
- {
- Console.WriteLine("Job1 执行");
- }
- }
- public class Job2 : IJob
- {
- public void Execute(IJobExecutionContext context)
- {
- Console.WriteLine("Job2 执行");
- }
- }
复制代码 3.作业执行中的数据传递
- using Quartz;
- using Quartz.Impl;
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- // 创建调度器工厂
- ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
- // 获取调度器实例
- IScheduler scheduler = schedulerFactory.GetScheduler().Result;
- // 创建带数据的作业
- IJobDetail job = JobBuilder.Create<DataPassingJob>()
- .WithIdentity("dataPassingJob", "group1")
- .UsingJobData("key1", "value1")
- .UsingJobData("key2", 123)
- .Build();
- // 创建触发器
- ITrigger trigger = TriggerBuilder.Create()
- .WithIdentity("dataPassingTrigger", "group1")
- .StartNow()
- .WithSimpleSchedule(x => x
- .WithIntervalInSeconds(20)
- .RepeatForever())
- .Build();
- // 将作业和触发器添加到调度器
- scheduler.ScheduleJob(job, trigger).Wait();
- // 启动调度器
- scheduler.Start().Wait();
- Console.WriteLine("Quartz.NET 已启动,按任意键退出...");
- Console.ReadKey();
- // 关闭调度器
- scheduler.Shutdown().Wait();
- }
- catch (SchedulerException se)
- {
- Console.WriteLine(se);
- }
- }
- }
- public class DataPassingJob : IJob
- {
- public void Execute(IJobExecutionContext context)
- {
- // 从作业执行上下文中获取传递的数据
- JobDataMap dataMap = context.JobDetail.JobDataMap;
- string value1 = dataMap.GetString("key1");
- int value2 = dataMap.GetInt("key2");
- Console.WriteLine($"作业执行中的数据:key1={value1}, key2={value2}");
- }
- }
复制代码 4.全局作业监听器
- using Quartz;
- using Quartz.Impl;
- using System;
- public class GlobalJobListener : IJobListener
- {
- public string Name => "GlobalJobListener";
- public Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken = default)
- {
- Console.WriteLine($"作业被否决:{context.JobDetail.Key}");
- return Task.CompletedTask;
- }
- public Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default)
- {
- Console.WriteLine($"准备执行作业:{context.JobDetail.Key}");
- return Task.CompletedTask;
- }
- public Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken = default)
- {
- Console.WriteLine($"作业执行完成:{context.JobDetail.Key}");
- return Task.CompletedTask;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- // 创建调度器工厂
- ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
- // 获取调度器实例
- IScheduler scheduler = schedulerFactory.GetScheduler().Result;
- // 添加全局作业监听器
- scheduler.ListenerManager.AddJobListener(new GlobalJobListener());
- // 创建作业
- IJobDetail job = JobBuilder.Create<SimpleJob>()
- .WithIdentity("simpleJob", "group1")
- .Build();
- // 创建触发器
- ITrigger trigger = TriggerBuilder.Create()
- .WithIdentity("simpleTrigger", "group1")
- .StartNow()
- .WithSimpleSchedule(x => x
- .WithIntervalInSeconds(20)
- .RepeatForever())
- .Build();
- // 将作业和触发器添加到调度器
- scheduler.ScheduleJob(job, trigger).Wait();
- // 启动调度器
- scheduler.Start().Wait();
- Console.WriteLine("Quartz.NET 已启动,按任意键退出...");
- Console.ReadKey();
- // 关闭调度器
- scheduler.Shutdown().Wait();
- }
- catch (SchedulerException se)
- {
- Console.WriteLine(se);
- }
- }
- }
- public class SimpleJob : IJob
- {
- public void Execute(IJobExecutionContext context)
- {
- Console.WriteLine("简单作业执行中...");
- }
- }
复制代码 5.全局触发器监听器
- using Quartz;
- using Quartz.Impl;
- using System;
- public class GlobalTriggerListener : ITriggerListener
- {
- public string Name => "GlobalTriggerListener";
- public Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, Trigger.CompletedExecutionInstruction triggerInstructionCode, CancellationToken cancellationToken = default)
- {
- Console.WriteLine($"触发器完成:{trigger.Key}");
- return Task.CompletedTask;
- }
- public Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
- {
- Console.WriteLine($"触发器触发:{trigger.Key}");
- return Task.CompletedTask;
- }
- public Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default)
- {
- Console.WriteLine($"触发器错过触发:{trigger.Key}");
- return Task.CompletedTask;
- }
- public Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default)
- {
- Console.WriteLine($"否决作业执行:{trigger.Key}");
- return Task.FromResult(false);
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- // 创建调度器工厂
- ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
- // 获取调度器实例
- IScheduler scheduler = schedulerFactory.GetScheduler().Result;
- // 添加全局触发器监听器
- scheduler.ListenerManager.AddTriggerListener(new GlobalTriggerListener());
- // 创建作业
- IJobDetail job = JobBuilder.Create<SimpleJob>()
- .WithIdentity("simpleJob", "group1")
- .Build();
- // 创建触发器
- ITrigger trigger = TriggerBuilder.Create()
- .WithIdentity("simpleTrigger", "group1")
- .StartNow()
- .WithSimpleSchedule(x => x
- .WithIntervalInSeconds(20)
- .RepeatForever())
- .Build();
- // 将作业和触发器添加到调度器
- scheduler.ScheduleJob(job, trigger).Wait();
- // 启动调度器
- scheduler.Start().Wait();
- Console.WriteLine("Quartz.NET 已启动,按任意键退出...");
- Console.ReadKey();
- // 关闭调度器
- scheduler.Shutdown().Wait();
- }
- catch (SchedulerException se)
- {
- Console.WriteLine(se);
- }
- }
- }
- public class SimpleJob : IJob
- {
- public void Execute(IJobExecutionContext context)
- {
- Console.WriteLine("简单作业执行中...");
- }
- }
复制代码 6.自定义日历
- using Quartz;
- using Quartz.Impl;
- using System;
- public class CustomCalendar : BaseCalendar
- {
- // 实现自定义的日历逻辑,这里简单演示一个排除周末的例子
- public override bool IsTimeIncluded(DateTimeOffset timeStampUtc)
- {
- return timeStampUtc.DayOfWeek != DayOfWeek.Saturday && timeStampUtc.DayOfWeek != DayOfWeek.Sunday;
- }
- public override DateTimeOffset GetNextIncludedTimeUtc(DateTimeOffset timeStampUtc)
- {
- // 确保下一个时间是在排除条件内的
- DateTimeOffset nextTime = timeStampUtc.AddSeconds(1);
- while (!IsTimeIncluded(nextTime))
- {
- nextTime = nextTime.AddSeconds(1);
- }
- return nextTime;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- // 创建调度器工厂
- ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
- // 获取调度器实例
- IScheduler scheduler = schedulerFactory.GetScheduler().Result;
- // 使用自定义日历
- scheduler.AddCalendar("customCalendar", new CustomCalendar(), true, true);
- // 创建作业
- IJobDetail job = JobBuilder.Create<SimpleJob>()
- .WithIdentity("simpleJob", "group1")
- .Build();
- // 创建触发器,关联自定义日历
- ITrigger trigger = TriggerBuilder.Create()
- .WithIdentity("simpleTrigger", "group1")
- .StartNow()
- .WithSimpleSchedule(x => x
- .WithIntervalInSeconds(20)
- .RepeatForever())
- .ModifiedByCalendar("customCalendar")
- .Build();
- // 将作业和触发器添加到调度器
- scheduler.ScheduleJob(job, trigger).Wait();
- // 启动调度器
- scheduler.Start().Wait();
- Console.WriteLine("Quartz.NET 已启动,按任意键退出...");
- Console.ReadKey();
- // 关闭调度器
- scheduler.Shutdown().Wait();
- }
- catch (SchedulerException se)
- {
- Console.WriteLine(se);
- }
- }
- }
- public class SimpleJob : IJob
- {
- public void Execute(IJobExecutionContext context)
- {
- Console.WriteLine("简单作业执行中...");
- }
- }
复制代码 7.集群模式
- using Quartz;
- using Quartz.Impl;
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- // 创建调度器工厂
- ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
- // 获取调度器实例,设置为集群模式
- IScheduler scheduler = schedulerFactory.GetScheduler(new NameValueCollection { { "quartz.jobStore.type", "Quartz.Simpl.RAMJobStore, Quartz" } }).Result;
- // 创建作业
- IJobDetail job = JobBuilder.Create<SimpleJob>()
- .WithIdentity("simpleJob", "group1")
- .Build();
- // 创建触发器
- ITrigger trigger = TriggerBuilder.Create()
- .WithIdentity("simpleTrigger", "group1")
- .StartNow()
- .WithSimpleSchedule(x => x
- .WithIntervalInSeconds(20)
- .RepeatForever())
- .Build();
- // 将作业和触发器添加到调度器
- scheduler.ScheduleJob(job, trigger).Wait();
- // 启动调度器
- scheduler.Start().Wait();
- Console.WriteLine("Quartz.NET 已启动,按任意键退出...");
- Console.ReadKey();
- // 关闭调度器
- scheduler.Shutdown().Wait();
- }
- catch (SchedulerException se)
- {
- Console.WriteLine(se);
- }
- }
- }
- public class SimpleJob : IJob
- {
- public void Execute(IJobExecutionContext context)
- {
- Console.WriteLine("简单作业执行中...");
- }
- }
复制代码 8.持久性作业
- using Quartz;
- using Quartz.Impl;
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- // 创建调度器工厂
- ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
- // 获取调度器实例,设置为使用 AdoJobStore 持久性存储
- IScheduler scheduler = schedulerFactory.GetScheduler(new NameValueCollection
- {
- { "quartz.jobStore.type", "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz" },
- { "quartz.jobStore.driverDelegateType", "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz" },
- { "quartz.jobStore.dataSource", "myDS" },
- { "quartz.dataSource.myDS.connectionString", "YourConnectionString" },
- { "quartz.jobStore.tablePrefix", "QRTZ_" },
- { "quartz.jobStore.useProperties", "true" },
- { "quartz.jobStore.misfireThreshold", "60000" }
- }).Result;
- // 创建作业
- IJobDetail job = JobBuilder.Create<SimpleJob>()
- .WithIdentity("simpleJob", "group1")
- .StoreDurably() // 设置为持久性作业
- .Build();
- // 创建触发器
- ITrigger trigger = TriggerBuilder.Create()
- .WithIdentity("simpleTrigger", "group1")
- .StartNow()
- .WithSimpleSchedule(x => x
- .WithIntervalInSeconds(20)
- .RepeatForever())
- .Build();
- // 将作业和触发器添加到调度器
- scheduler.AddJob(job, true).Wait();
- scheduler.ScheduleJob(trigger).Wait();
- // 启动调度器
- scheduler.Start().Wait();
- Console.WriteLine("Quartz.NET 已启动,按任意键退出...");
- Console.ReadKey();
- // 关闭调度器
- scheduler.Shutdown().Wait();
- }
- catch (SchedulerException se)
- {
- Console.WriteLine(se);
- }
- }
- }
- public class SimpleJob : IJob
- {
- public void Execute(IJobExecutionContext context)
- {
- Console.WriteLine("简单作业执行中...");
- }
- }
复制代码 9.作业状态记录
- using Quartz;
- using Quartz.Impl;
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- // 创建调度器工厂
- ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
- // 获取调度器实例
- IScheduler scheduler = schedulerFactory.GetScheduler().Result;
- // 创建作业
- IJobDetail job = JobBuilder.Create<StatusRecordingJob>()
- .WithIdentity("statusRecordingJob", "group1")
- .Build();
- // 创建触发器
- ITrigger trigger = TriggerBuilder.Create()
- .WithIdentity("statusRecordingTrigger", "group1")
- .StartNow()
- .WithSimpleSchedule(x => x
- .WithIntervalInSeconds(20)
- .RepeatForever())
- .Build();
- // 将作业和触发器添加到调度器
- scheduler.ScheduleJob(job, trigger).Wait();
- // 启动调度器
- scheduler.Start().Wait();
- Console.WriteLine("Quartz.NET 已启动,按任意键退出...");
- Console.ReadKey();
- // 关闭调度器
- scheduler.Shutdown().Wait();
- }
- catch (SchedulerException se)
- {
- Console.WriteLine(se);
- }
- }
- }
- public class StatusRecordingJob : IJob
- {
- public void Execute(IJobExecutionContext context)
- {
- // 记录作业状态
- Console.WriteLine($"作业执行中... 执行状态:{context.Result}");
- }
- }
复制代码 10.并行执行
- using Quartz;
- using Quartz.Impl;
- using System;
- using System.Threading.Tasks;
- class Program
- {
- static async Task Main(string[] args)
- {
- try
- {
- // 创建调度器工厂
- ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
- // 获取调度器实例
- IScheduler scheduler = await schedulerFactory.GetScheduler();
- // 创建作业1
- IJobDetail job1 = JobBuilder.Create<ParallelJob>()
- .WithIdentity("parallelJob1", "group1")
- .Build();
- // 创建作业2
- IJobDetail job2 = JobBuilder.Create<ParallelJob>()
- .WithIdentity("parallelJob2", "group1")
- .Build();
- // 创建触发器1
- ITrigger trigger1 = TriggerBuilder.Create()
- .WithIdentity("trigger1", "group1")
- .StartNow()
- .Build();
- // 创建触发器2
- ITrigger trigger2 = TriggerBuilder.Create()
- .WithIdentity("trigger2", "group1")
- .StartNow()
- .Build();
- // 将作业和触发器添加到调度器
- await scheduler.ScheduleJob(job1, trigger1);
- await scheduler.ScheduleJob(job2, trigger2);
- // 启动调度器
- await scheduler.Start();
- Console.WriteLine("Quartz.NET 已启动,按任意键退出...");
- Console.ReadKey();
- // 关闭调度器
- await scheduler.Shutdown();
- }
- catch (SchedulerException se)
- {
- Console.WriteLine(se);
- }
- }
- }
- public class ParallelJob : IJob
- {
- public async Task Execute(IJobExecutionContext context)
- {
- // 模拟作业执行时间
- await Task.Delay(TimeSpan.FromSeconds(10));
- Console.WriteLine($"并行作业执行中... 执行时间:{DateTime.Now}");
- }
- }
复制代码 这些示例涵盖了 Quartz.NET 的一些高级功能,包括 Cron 表达式触发器、作业间的依赖性、作业执行中的数据传递、全局作业监听器、全局触发器监听器、自定义日历、集群模式、持久性作业、作业状态记录和并行执行。希望对你理解 Quartz.NET 的高级功能有所帮助。
来源:https://www.cnblogs.com/hanbing81868164/archive/2023/12/20/17915291.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作! |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
x
|