[英]Quartz in ASP.net Core project: how to get the scheduler instance
I have an ASP.net Core 6
project where I added Quartz
to my services, like described here:我有一个ASP.net Core 6
项目,我在服务中添加了Quartz
,如下所述:
https://www.quartz-scheduler.net/documentation/quartz-3.x/packages/aspnet-core-integration.html#installation https://www.quartz-scheduler.net/documentation/quartz-3.x/packages/aspnet-core-integration.html#installation
This works and allows you to configure jobs and triggers during app startup.这有效并允许您在应用程序启动期间配置作业和触发器。
However, what if I want to modify/add/remove a job or trigger while the app is running?但是,如果我想在应用程序运行时修改/添加/删除作业或触发器怎么办? I would need to retrieve the underlying IScheduler
instance (ideally through the DI mechanism), but I don't know the proper way to do it in an ASP.net Core app.我需要检索底层IScheduler
实例(最好通过 DI 机制),但我不知道在 ASP.net 核心应用程序中执行此操作的正确方法。
So, how can you access the scheduler instance from DI in a .net core project?那么,如何在 .net 核心项目中从 DI 访问调度程序实例?
After looking at the Quartz source code, I've understood how to do this.在查看了 Quartz 源代码之后,我明白了如何做到这一点。
Indeed, you cannot inject IScheduler
, in fact it wouldn't make much sense because you can have multiple schedulers configured, so the DI container would have no way to decide which one to inject.实际上,您不能注入IScheduler
,实际上这没有多大意义,因为您可以配置多个调度程序,因此 DI 容器将无法决定注入哪个调度程序。
Instead, you need to inject ISchedulerFactory
, which you can then use to retrieve one of the configured schedulers.相反,您需要注入ISchedulerFactory
,然后您可以使用它来检索配置的调度程序之一。
Example code:示例代码:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddQuartz(q => {
//configuring basic Quartz settings...
}
//Other configs...
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var schedulerFactory = scope.ServiceProvider.GetService<ISchedulerFactory>();
var scheduler = await schedulerFactory.GetScheduler();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.