定时任务:在时间轴上,在某一个时刻,去执行某一个任务!随着时间轴循环往复;
调用服务:就是指定的时间点去做什么事 循环往复(时间策略)
Quartz框架的使用:
1、NuGet添加引用(注意版本所依赖的.Net版本)
2、IScheduler:单元/实例,在这里去完成定时任务的配置,只有单元启动,里面的作业才能正常执行;
/// <summary>
/// 初始化 Quartz注意依赖的.Net版本
/// </summary>
/// <returns></returns>
public async static Task Init()
{
//创建单元(时间轴/载体)
StdSchedulerFactory factory = new StdSchedulerFactory();
IScheduler scheduler = await factory.GetScheduler();
await scheduler.Start();
#region 添加监听
scheduler.ListenerManager.AddJobListener(new CustomJobListener());
scheduler.ListenerManager.AddTriggerListener(new CustomTriggerListener());
scheduler.ListenerManager.AddSchedulerListener(new CustomSchedulerListener());
#endregion
//Job (作业) 生成了一个描述
IJobDetail jobDetail = JobBuilder.Create<SendMessageJob>()
.WithIdentity("SendMessageJob","group1")//指定分组
.WithDescription("this is Send Message Job")//添加描述
.Build();
//通过 jobDetail,传入参数
jobDetail.JobDataMap.Add("person1","张三");
jobDetail.JobDataMap.Add("person2", "李四");
jobDetail.JobDataMap.Add("person3", "王五");
jobDetail.JobDataMap.Add("Age", 8);
//时间策略
//ITrigger trigger = TriggerBuilder.Create()
// .WithIdentity("SendMessageTrigger", "group1")
// //.StartAt(new DateTimeOffset()) //从某个时间点开始
// .StartNow() //马上执行了一次
// .WithSimpleSchedule(w=>w.WithIntervalInSeconds(5).WithRepeatCount(3))//WithRepeatCount =>最多执行三次 WithIntervalInSeconds=>5秒执行 .RepeatForever() =>循环往复
// .Build();
//Cron
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("SendMessageTrigger", "group1")
.StartAt(new DateTimeOffset(DateTime.Now.AddSeconds(10))) //从某个时间点开始
//.StartNow() //马上执行了一次
.WithCronSchedule("5/10 * * * * ?")//从5开始每间隔10s执行一次
.WithDescription("This is test job ")
.Build();
//通过 ITrigger 传入参数
trigger.JobDataMap.Add("person5", "赵六");
trigger.JobDataMap.Add("person6", "王琦");
trigger.JobDataMap.Add("Age", 90);
//把时间策略和作业加入到单元上
await scheduler.ScheduleJob(jobDetail, trigger);
}
IIJob:定时执行的动作就是Job;
ITrigger:定时策略
[PersistJobDataAfterExecution]//执行后的保留作业数据
[DisallowConcurrentExecution] //确保上次任务执行完成后 再执行下一次任务
public class SendMessageJob : IJob
{
//每执行一次 就创建一个对象 无状态
public SendMessageJob()
{
//Console.WriteLine("SendMessageJob 执行了");
}
/// <summary>
/// 当前Task内部就是作业体要执行的任务
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task Execute(IJobExecutionContext context)
{
await Task.Run(()=> {
//Thread.Sleep(8000);
object person1 = context.JobDetail.JobDataMap.Get("person1");
string person2 = context.JobDetail.JobDataMap.GetString("person2");
string person3 = context.JobDetail.JobDataMap.GetString("person3");
int age = context.JobDetail.JobDataMap.GetInt("Age");
Console.WriteLine($"person1:{person1},person2:{person2},person3:{person3},age:{age},开始任务,时间:{DateTime.Now}");
object person5 = context.Trigger.JobDataMap.Get("person5");
object person6 = context.Trigger.JobDataMap.Get("person6");
int person7_Age = context.Trigger.JobDataMap.GetInt("Age");
//使用这个MergedJobDataMap 获取参数 以后者为准
object ages = context.MergedJobDataMap.Get("Age");
//需要使用上一次结果
context.JobDetail.JobDataMap.Put("Age", age + 1);
Console.WriteLine($"person5:{person5},person6:{person6},person7_Age:{person7_Age},age:{ages},时间:{DateTime.Now}");
});
}
}
3、SchedulerListener
public class CustomSchedulerListener : ISchedulerListener
{
public async Task JobAdded(IJobDetail jobDetail, CancellationToken cancellationToken = default(CancellationToken))
{
await Task.Run(()=> {
Console.WriteLine($"{jobDetail.Key.Name} 添加进来");
});
}
public async Task JobDeleted(JobKey jobKey, CancellationToken cancellationToken = default(CancellationToken))
{
await Task.Run(() =>
{
Console.WriteLine($"{jobKey.Name} 添加进来");
});
}
public Task JobInterrupted(JobKey jobKey, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task JobPaused(JobKey jobKey, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task JobResumed(JobKey jobKey, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task JobScheduled(ITrigger trigger, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task JobsPaused(string jobGroup, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task JobsResumed(string jobGroup, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task JobUnscheduled(TriggerKey triggerKey, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task SchedulerError(string msg, SchedulerException cause, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task SchedulerInStandbyMode(CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task SchedulerShutdown(CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task SchedulerShuttingdown(CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task SchedulerStarted(CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task SchedulerStarting(CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task SchedulingDataCleared(CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task TriggerFinalized(ITrigger trigger, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task TriggerPaused(TriggerKey triggerKey, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task TriggerResumed(TriggerKey triggerKey, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task TriggersPaused(string triggerGroup, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
public Task TriggersResumed(string triggerGroup, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
}
4、TriggerListener
public class CustomTriggerListener : ITriggerListener
{
public string Name => "CustomTriggerListener";
public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default(CancellationToken))
{
await Task.Run(()=> {
Console.WriteLine("this is TriggerComplete");
});
}
public async Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
{
await Task.Run(() =>
{
Console.WriteLine("this is TriggerFired");
});
}
public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default(CancellationToken))
{
await Task.Run(() =>
{
Console.WriteLine("this is TriggerMisfired");
});
}
/// <summary>
/// 当前任务 是否被取消 返回false 就继续执行 返回true就被取消了
/// </summary>
/// <param name="trigger"></param>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
{
await Task.Run(() =>
{
Console.WriteLine("this is VetoJobExecution");
});
return false;
}
}
5、JobListener
/// <summary>
/// 可以做些记录
/// </summary>
public class CustomJobListener : IJobListener
{
public string Name => "CustomJobListener";
/// <summary>
/// 执行中断 触发
/// </summary>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
{
await Task.Run(()=> {
Console.WriteLine("this is JobExecutionVetoed");
});
}
/// <summary>
/// 即将被执行 触发
/// </summary>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
{
await Task.Run(() =>
{
Console.WriteLine("this is JobToBeExecuted");
});
}
/// <summary>
/// 执行完毕后 触发
/// </summary>
/// <param name="context"></param>
/// <param name="jobException"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken = default(CancellationToken))
{
await Task.Run(() =>
{
Console.WriteLine("this is JobWasExecuted");
});
}
}
6、日志
public class CustomConsoleLogProvider : ILogProvider
{
public Logger GetLogger(string name)
{
return new Logger((level, func, exception, parameter) => {
if (level>= LogLevel.Info && func!=null)
{
Console.WriteLine($"[{DateTime.Now.ToLongTimeString()}] [{level}] {func()} {string.Join(":",parameter.Select(p=>p==null?"":p.ToString()))} 自定义日志:{name}");
}
return true;
});
}
public IDisposable OpenMappedContext(string key, string value)
{
throw new NotImplementedException();
}
public IDisposable OpenNestedContext(string message)
{
throw new NotImplementedException();
}
}
7、主函数中调用
class Program
{
/// <summary>
///
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
DispatchingManager.Init().GetAwaiter().GetResult();
System.Console.ReadKey();
}
}