.net core中使用Quartz任务调度
使用xml配置Quartz任务调度程序
1、Nuget
Install-Package Quartz Install-Package Quartz.Plugins
2、站点根目录下加入文件quartz.config、quartz_jobs.xml,(注意需要设置“复制到输出目录”为始终复制)文件名称默认:
quartz.config:
# You can configure your scheduler in either <quartz> configuration section # or in quartz properties file # Configuration section has precedence quartz.scheduler.instanceName = ServerScheduler # configure thread pool info quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz quartz.threadPool.threadCount = 10 quartz.threadPool.threadPriority = Normal # job initialization plugin handles our xml reading, without it defaults are used quartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins quartz.plugin.xml.fileNames = ~/quartz_jobs.xml
quartz_jobs.xml:
<?xml version="1.0" encoding="UTF-8"?> <job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"> <processing-directives> <overwrite-existing-data>true</overwrite-existing-data> </processing-directives> <schedule> <job> <name>TestJob</name> <group>DefaultJobGroup</group> <description>任务描述</description> <job-type>TestQuartzService.TestJob,TestQuartzService</job-type> <durable>true</durable> <recover>false</recover> </job> <trigger> <cron> <name>TestTrigger</name> <group>DefaultJobTriggerGroup</group> <job-name>TestJob</job-name> <job-group>DefaultJobGroup</job-group> <misfire-instruction>DoNothing</misfire-instruction> <cron-expression>*/5 * * * * ?</cron-expression> </cron> </trigger> </schedule> </job-scheduling-data>
3、创建QuartzFactory.cs,名称自定义:
public static void Start() { StdSchedulerFactory factory = new StdSchedulerFactory(); IScheduler scheduler = factory.GetScheduler().Result; Schedulers.Add(scheduler); scheduler.Start(); }
4、最后定义业务job,实现IJob接口
public class TestJob : IJob { public Task Execute(IJobExecutionContext context) { return Task.Run(() => { //业务操作 }); } }
在IJob实现类中实现构造函数的参数注入
1、实现IJobFactory接口
/// <summary> /// 任务调度工厂实现,为了调用作业的参数构造函数,Quartz.NET提供了IJobFactory接口 /// </summary> public class DemoFactory : IJobFactory { private readonly IServiceProvider _serviceProvider; public DemoFactory(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) { var jobDetail = bundle.JobDetail; var job = (IJob)_serviceProvider.GetService(jobDetail.JobType); return job; } public void ReturnJob(IJob job) { var disposable = job as IDisposable; disposable?.Dispose(); } }
2、通过IServiceCollection注册IJob实现类
var listServices = ReflectorHelper.GetTClassName("IJob实现类所在的程序集名称"); //ReflectorHelper 为程序集反射工具类 foreach (var item in listServices) {
services.AddScoped(item);
}
3、使用实现的工厂,为了调用作业的参数构造函数
Start中设置:
scheduler.JobFactory = new DemoFactory(services.BuildServiceProvider());
4、Startup中启动:
QuartzFactory.Start();