Quartz.Net_快速开始
简述
Quartz中主要分为三部分,JobDetail、Trigger、Scheduler,分别是任务、触发器、调度器,三者的关系为:Trigger控制JobDetail的执行时间和频率,而Scheduler负责将具体的Trigger与具体的JobDetail绑定
1.安装Quartz依赖
2.编写代码
①实现IJob接口与创建JobDetail
实现IJob接口
public class MyJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
// context.ScheduledFireTimeUtc?.LocalDateTime 执行时间
// context.NextFireTimeUtc?.LocalDateTime 下次执行时间
Console.WriteLine($"任务执行:{DateTime.Now}");
Console.WriteLine($"执行时间:{context.ScheduledFireTimeUtc?.LocalDateTime}");
Console.WriteLine($"下次执行时间:{context.NextFireTimeUtc?.LocalDateTime}");
await Task.CompletedTask;
}
}
创建JobDetail
public class JobDetailGetter
{
public static IJobDetail GetJobDetail<T>(JobKey name) where T : IJob
{
return JobBuilder.Create<T>()
.WithIdentity(name)
.Build();
}
}
Execute函数中的代码即为定时任务执行的操作
②创建Trigger
var triggerBuilder = TriggerBuilder.Create()
//.StartNow()
.StartAt(startTime)
.EndAt(endTime)
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(intervalInSeconds) // 设置时间间隔: 秒
//.WithRepeatCount(10) // 设置间隔时长
.RepeatForever());
public class TriggerGetter
{
public static ITrigger GetSecondsTrigger(DateTimeOffset startTime, DateTimeOffset endTime, int intervalInSeconds)
{
// Trigger构造器
var triggerBuilder = TriggerBuilder.Create()
//.StartNow()
.StartAt(startTime)
.EndAt(endTime)
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(intervalInSeconds) // 设置时间间隔: 秒
//.WithRepeatCount(10) // 设置间隔时长
.RepeatForever());
// 构造并返回Trigger
return triggerBuilder.Build();
}
}
③创建Scheduler(建议使用单例封装)
public class SchedulerGetter
{
// 由CLR保证: 在程序第一次使用该类之前被调用, 而且只调用一次
private static readonly IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler().Result;
public static async Task<IScheduler> GetSchedulerAsync()
{
return scheduler;
}
}
3.测试
static async Task Main(string[] args)
{
IScheduler scheduler = await SchedulerGetter.GetSchedulerAsync();
var startTime = new DateTimeOffset(DateTime.Now);
var endTime = new DateTimeOffset(DateTime.Now.AddSeconds(10));
ITrigger trigger = TriggerGetter.GetSecondsTrigger(startTime, endTime, 3);
IJobDetail jobDetail = JobDetailGetter.GetJobDetail<MyJob>(new JobKey("ABC"));
await scheduler.ScheduleJob(jobDetail, trigger);
Thread.Sleep(10000);
}