如何在Quartz.net中使用DI使用添加的调度器



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

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)中创建的调度程序。

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

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

应该是这样的:

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();
}

最新更新