项目中需要用到quartz执行定时任务,在此记录一下学习过程。
quartz安装
在vs2022中,通过nuget包管理器安装quartz 3.8.1 ,这是.net 6 依赖的最高版本。
创建定时器任务
1、创建quartzconfigurator
新建quartzconfiguratorextensions类,用于注册触发器和任务,代码如下:
/// <summary> /// 添加任务和触发器 /// </summary> /// <typeparam name="t"></typeparam> /// <param name="quartz"></param> /// <param name="config"></param> /// <exception cref="exception"></exception> public static void addjobandtrigger<t>(this iservicecollectionquartzconfigurator quartz, iconfiguration config) where t : ijob { // use the name of the ijob as the appsettings.json key string jobname = typeof(t).name; // try and load the schedule from configuration var configkey = $"quartz:{jobname}"; var cronschedule = config[configkey]; // some minor validation if (string.isnullorempty(cronschedule)) { throw new exception($"no quartz.net cron schedule found for job in configuration at {configkey}"); } // register the job as before var jobkey = new jobkey(jobname); quartz.addjob<t>(opts => opts.withidentity(jobkey)); quartz.addtrigger(opts => opts .forjob(jobkey) .withidentity(jobname + "-trigger") .withcronschedule(cronschedule)); // use the schedule from configuration } /// <summary> /// 添加任务和触发器(带参数传递) /// </summary> /// <typeparam name="t"></typeparam> /// <param name="quartz"></param> /// <param name="config"></param> /// <param name="keyvaluepairs">需要传递的参数</param> /// <param name="istriggerjobdatamap">默认通过 工作描述时传递参数</param> /// <exception cref="exception"></exception> public static void addjobandtriggerwithparameter<t>(this iservicecollectionquartzconfigurator quartz, iconfiguration config, idictionary<string, object>? keyvaluepairs = null, bool isjobdetailjobdatamap = true) where t : ijob { // use the name of the ijob as the appsettings.json key string jobname = typeof(t).name; // try and load the schedule from configuration var configkey = $"quartz:{jobname}"; var cronschedule = config[configkey]; // some minor validation if (string.isnullorempty(cronschedule)) { throw new exception($"no quartz.net cron schedule found for job in configuration at {configkey}"); } // register the job as before var jobkey = new jobkey(jobname); if (keyvaluepairs != null && isjobdetailjobdatamap) { switch (isjobdetailjobdatamap) { case true: quartz.addjob<t>(opts => opts .withidentity(jobkey) .usingjobdata(new jobdatamap(keyvaluepairs))); quartz.addtrigger(opts => opts .forjob(jobkey) .withidentity(jobname + "-trigger") .withcronschedule(cronschedule)); // use the schedule from configuration break; case false: quartz.addjob<t>(opts => opts .withidentity(jobkey)); quartz.addtrigger(opts => opts .forjob(jobkey) .withidentity(jobname + "-trigger") .withcronschedule(cronschedule) .usingjobdata(new jobdatamap(keyvaluepairs))); // use the schedule from configuration break; } } else { quartz.addjob<t>(opts => opts .withidentity(jobkey)); quartz.addtrigger(opts => opts .forjob(jobkey) .withidentity(jobname + "-trigger") .withcronschedule(cronschedule)); // use the schedule from configuration } }
2、在program.cs 中注入服务
builder.services.addquartz(q => { 创建计划单元(时间轴,载体) //stdschedulerfactory schedulerfactory = new stdschedulerfactory(); //var scheduler = await schedulerfactory.getscheduler(); //await scheduler.start(); q.usemicrosoftdependencyinjectionjobfactory(); // register the job, loading the schedule from configuration q.addjobandtrigger<fromkingdeeworkerjob>(builder.configuration); }); builder.services.addquartzhostedservice(q => q.waitforjobstocomplete = true);
3、创建工作单元workerjob
新建类testworkerjob,并继承ijob,代码如下:
[persistjobdataafterexecution]//在执行完成后,保留jobdatamap数据 [disallowconcurrentexecution]//不允许并发执行,即必须等待上次完成后才能执行下一次 public class testworkerjob : ijob { private readonly ilogger<testeworkerjob> _logger; public testworkerjob(ilogger<testworkerjob> logger) { _logger = logger; } public task execute(ijobexecutioncontext context) { _logger.loginformation(datetime.now +" --- hello world!"); task.delay(50000); thread.sleep(10000); return task.completedtask; } }
假如我们的定时任务,执行一次需要耗时比较久,而且后一次执行需要等待前一次完成,并且需要前一次执行的结果作为参考,那么就需要设置任务的任性。因为默认情况下,工作单元在每一次运行都是一个新的实例,相互之间独立运行,互不干扰。所以如果需要存在一定的关联,就要设置任务的特性,主要有两个,如下所示:
[persistjobdataafterexecution]//在执行完成后,保留jobdatamap数据
[disallowconcurrentexecution]//不允许并发执行,即必须等待上次完成后才能执行下一次
以上两个特性,只需要标记在任务对应的类上即可。
4、appsettings.json配置
在appsettings.json文件中添加一项quartz,子项的必须与workerjob的名字保持一致,value是cron表达式
{ "quartz": { "fromkingdeeworkerjob": "0/5 * * * * ?" } }
然后,启动项目,就可以看到任务可以正常运行啦。
最后
最后附上学习链接,
到此这篇关于.net 6 配置quartz定时任务的文章就介绍到这了,更多相关.net 6 quartz定时任务内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论