安裝 Quartz 套件
必須安裝兩個套件
- Quartz
- Quartz.Extensions.Hosting:V3.2 時出現,詳見官方文章 - Hosted Services Integration
建立 Quartz Job
把 Log DI 注入後,使用 LogWarming 在畫面上輸出文字
using Quartz;
namespace QuartzWorkerSample
{
[DisallowConcurrentExecution]
public class HelloWorldJob : IJob
{
private readonly ILogger<HelloWorldJob> _logger;
public HelloWorldJob(ILogger<HelloWorldJob> logger)
{
_logger = logger;
}
public Task Execute(IJobExecutionContext context)
{
_logger.LogWarning($"Hello World {DateTime.Now} and Jobtype: {context.JobDetail.JobType}");
return Task.CompletedTask;
}
}
}
會有兩個文字輸出,分別為
- QuartzHostedService:每 5 秒輸出
- BackgroundService:即為 .NET 8 預設 Worker,每 1 秒輸出
C# 語法
using Quartz;
namespace QuartzWorkerSample
{
public class Program
{
public static void Main(string[] args)
{
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddQuartz(config =>
{
config.AddJob<HelloWorldJob>(config => config
.WithIdentity(nameof(HelloWorldJob)));
config.AddTrigger(config => config
.ForJob(nameof(HelloWorldJob))
.WithIdentity("HelloWorldJob-Trigger")
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(5) // 每五秒觸發一次
.RepeatForever()));
});
// QuartzHostedService 實作 IHostService
builder.Services.AddQuartzHostedService(options => options
.WaitForJobsToComplete = true);
// 該 Worker 為 .NET 8 預設範本
builder.Services.AddHostedService<Worker>();
var host = builder.Build();
host.Run();
}
}
}
執行結果
網路教學常見語法
builder.Services.AddQuartz(config =>
{
config.UseMicrosoftDependencyInjectionScopedJobFactory();
config.UseMicrosoftDependencyInjectionJobFactory();
});
UseMicrosoftDependencyInjectionScopedJobFactory 在 V3.3.2 開始 Job Factory 為 Scoped Jobs,不在需要使用它,詳見官方文章 - Microsoft DI Integration
UseMicrosoftDependencyInjectionJobFactory 在 V3.7 時 MS DI 變成預設 DI,不需要去設定,詳見 V3.7 release 和 討論
看到這兩個語法就把它 pass 掉吧