如何在 Quartz.net 中通过 DI 使用添加的调度程序

How to use added scheduler using DI in Quartz.net

我在服务启动中添加了调度程序,例如:

services.AddQuartz(q =>
{
    q.SchedulerId = "S1";
    q.SchedulerName = "S1";
    
    q.UseMicrosoftDependencyInjectionJobFactory();

    q.UsePersistentStore(s =>
    {
        s.UseProperties = true;
        s.UsePostgres("ConnectionString");
      
        s.UseJsonSerializer();
    });
})

现在我尝试通过 DI 使用这个创建的调度程序,例如:

public SchedulerStartup(ISchedulerFactory schedulerFactory)
{
    this.schedulerFactory = schedulerFactory;
}

public async Task StartAsync(CancellationToken cancellationToken)
{
    Scheduler = await schedulerFactory.GetScheduler("S1", cancellationToken);
    
    await Scheduler.Start(cancellationToken);
}

但不知何故 Scheduler 为空。我无法访问在启动配置中创建的调度程序 (S1)。

Link: https://www.quartz-scheduler.net/documentation/quartz-3.x/packages/microsoft-di-integration.html#di-aware-job-factories

这里我错过了 services.AddQuartzHostedService() 使用托管服务启动调度程序。不需要额外启动 class。

应该是这样的:

services.AddQuartz(q =>
 {
     q.SchedulerName = "S1";

     q.UseMicrosoftDependencyInjectionJobFactory();
     
     q.UsePersistentStore(s =>
     {
         s.UseProperties = true;
         s.UsePostgres(DbConnectionString);
         s.UseJsonSerializer();
     });
 });

 services.AddQuartzHostedService(options =>
 {
     options.WaitForJobsToComplete = true;
 });

稍后创建的此 Scheduler 实例可用作 (S1):

public MyRuntimeScheduler(ISchedulerFactory schedulerFactory)
{
     Scheduler = schedulerFactory.GetScheduler("S1").GetAwaiter().GetResult();
}