Quartz With Hosted Services演示
轻量级演示,Quartz大部分设置使用了默认值
-
新建项目 && 安装Nuget包
- 新建ClassLibrary(QuartzJobService1),负责定义Job处理业务逻辑
- 新建WorkerService(QuartzWorkerService1),项目引用QuartzJobService1,负责配置和启动Quartz,该项目也可替换成其他启动项目,比如Asp.NetCore
Project Install Package # QuartzJobService1 Quartz 需要实现 IJob QuartzWorkerService1 Quartz.Extensions.Hosting 集成 hosted services Quartz.Plugins 解析 quartz_job_data.xml -
修改 Program.cs
IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices((context,services) => { //required services.AddQuartz(q => { }); services.AddQuartzHostedService(options => { // when shutting down we want jobs to complete gracefully options.WaitForJobsToComplete = true; }); //services.AddHostedService<Worker>(); }) .Build();
-
F5调试查看效果
-
QuartzJobService1 新建 TheJob.cs
namespace QuartzJobService1 { public class TheJob : IJob { private readonly ILogger _logger; public TheJob(ILogger<TheJob> logger) { _logger = logger; } public Task Execute(IJobExecutionContext context) { _logger.LogInformation($"{nameof(TheJob)}: {DateTime.Now:G}"); return Task.CompletedTask; } } }
-
编辑 Program.cs
services.Configure<QuartzOptions>(context.Configuration.GetSection("Quartz")); services.AddTransient<TheJob>(); //required services.AddQuartz(q => { q.UseMicrosoftDependencyInjectionJobFactory(); });
-
编辑 appsettings.Development.json
{ "Logging": { ... }, "Quartz": { "quartz.plugin.jobInitializer.type": "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin,Quartz.Plugins", "quartz.plugin.jobInitializer.fileNames": "quartz_job_data.xml", "quartz.plugin.jobInitializer.failOnFileNotFound": true } }
-
QuartzWorkerService1 新建 quartz_job_data.xml
<?xml version="1.0" encoding="utf-8" ?> <job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData"> <schedule> <job> <name>theJob</name> <job-type>QuartzJobService1.TheJob, QuartzJobService1</job-type> </job> <trigger> <cron> <name>theJobTrigger</name> <job-name>theJob</job-name> <cron-expression>0/2 * * * * ?</cron-expression> </cron> </trigger> </schedule> </job-scheduling-data>
-
部署:发布直接执行QuartzWorkerService1.exe即可
-
-
QuartzWorkerService1 安装Nuget包 Microsoft.Extensions.Hosting.WindowsServices
-
Edit Program
IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices((context, services) => { ... }) .UseWindowsService() .Build();
-
cmd
sc.exe create QuartzWorkerService1 binPath=%~dp0QuartzWorkerService1.exe start=auto sc.exe start QuartzWorkerService1 sc.exe stop QuartzWorkerService1 sc.exe delete QuartzWorkerService1
-