概述
直接上代码,定时任务和策略 :
添加nuget包:Quartz(注意:依赖项,NETFranmework的版本,3.0基于最低版本4.5.2;)
public class Program
{
//IJob:任务,定时执行
//ITriagger:策略
public static void Main(string[] args)
{
ScheduleTest().GetAwaiter().GetResult();
Console.ReadLine();
}
public async static Task ScheduleTest()
{
StdSchedulerFactory factory = new StdSchedulerFactory();
IScheduler scheduler = await factory.GetScheduler();
await scheduler.Start();
{
Console.WriteLine("初始化Schedule:。。。");
IJobDetail jobDetail = JobBuilder.Create<TestJob>()
.WithIdentity("testJob", "group1")
.WithDescription("This is TestJob")
.Build();
jobDetail.JobDataMap.Add("李","白");
jobDetail.JobDataMap.Add("杜", "甫");
jobDetail.JobDataMap.Add("Times", DateTime.Now);
jobDetail.JobDataMap.Add("Wu", "五2019");
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("testtrigger1", "group1")
.StartAt(new DateTimeOffset(DateTime.Now.AddSeconds(10)))
.WithCronSchedule("0/10 * * * * ? ")
.WithDescription("This is testJob's Trigger")
.Build();
trigger.JobDataMap.Add("苏", "轼");
trigger.JobDataMap.Add("李", "清照");
trigger.JobDataMap.Add("Year", DateTime.Now.Year);
trigger.JobDataMap.Add("Wu", "五2020");
await scheduler.ScheduleJob(jobDetail, trigger);
Console.WriteLine("Schedule作业添加完成:。。。");
}
}
}
//分割线-----------------------------------------------------------------------------------------------------------------------------------------------------------
//添加Job工作任务逻辑
public class TestJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
await Task.Run(() =>
{
Console.WriteLine("**************************************");
Console.WriteLine($"This is{Thread.CurrentThread.ManagedThreadId}__{DateTime.Now}");
{
//获取JobDetail传递的参数值
JobDataMap dataMap = context.JobDetail.JobDataMap;
Console.WriteLine(dataMap.Get("李"));
Console.WriteLine(dataMap.Get("杜"));
Console.WriteLine(dataMap.Get("Times"));
}
{
//获取Trigger传递的参数值
JobDataMap dateMapIJ = context.Trigger.JobDataMap;
Console.WriteLine(dateMapIJ.Get("苏"));
Console.WriteLine(dateMapIJ.Get("李"));
Console.WriteLine(dateMapIJ.Get("Year"));
Console.WriteLine("**************************************");
}
{
//获取MergedJobDataMap传递的参数值,合并IJobDetail和ITrigger以最后一个为准
JobDataMap dateMapMJ = context.MergedJobDataMap;
Console.WriteLine(dateMapMJ.Get("李"));
Console.WriteLine(dateMapMJ.Get("杜"));
Console.WriteLine(dateMapMJ.Get("Times"));
Console.WriteLine("----");
Console.WriteLine(dateMapMJ.Get("苏"));
Console.WriteLine(dateMapMJ.Get("李"));
Console.WriteLine(dateMapMJ.Get("Year"));
Console.WriteLine(dateMapMJ.Get("Wu"));//这里是2020
Console.WriteLine("**************************************");
}
Console.WriteLine();
});
}
}
最后
以上就是眼睛大枫叶为你收集整理的Quartz调度器的全部内容,希望文章能够帮你解决Quartz调度器所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复