.NET Core Web Api 配置Quartz
时间: 2024-06-08 11:07:05 浏览: 206
.NetCore 中使用QuartZ
5星 · 资源好评率100%
Quartz是一个流行的开源任务调度框架,可以帮助我们在.NET Core Web Api中进行任务调度。下面是配置Quartz的步骤:
1. 安装Quartz NuGet包:在Visual Studio中打开NuGet包管理器控制台,运行以下命令安装Quartz NuGet包:
```
Install-Package Quartz
```
2. 创建Job类:创建一个继承自IJob接口的Job类,实现Execute方法。在这个方法中,你可以编写你的任务逻辑。
```
public class MyJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
// 编写任务逻辑
}
}
```
3. 配置Scheduler:在Startup.cs文件中,添加以下代码来配置Scheduler:
```
services.AddSingleton<IJobFactory, QuartzJobFactory>();
services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
services.AddSingleton(new JobSchedule(
jobType: typeof(MyJob),
cronExpression: "0 0/5 * * * ?")); // 每5分钟执行一次任务
services.AddHostedService<QuartzHostedService>();
```
4. 创建JobSchedule类:创建一个JobSchedule类,用于存储Job的类型和Cron表达式。
```
public class JobSchedule
{
public JobSchedule(Type jobType, string cronExpression)
{
JobType = jobType;
CronExpression = cronExpression;
}
public Type JobType { get; }
public string CronExpression { get; }
}
```
5. 创建QuartzJobFactory类:创建一个实现IJobFactory接口的QuartzJobFactory类,用于创建Job实例。
```
public class QuartzJobFactory : IJobFactory
{
private readonly IServiceProvider _serviceProvider;
public QuartzJobFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
return (IJob)_serviceProvider.GetService(bundle.JobDetail.JobType);
}
public void ReturnJob(IJob job)
{
// do nothing
}
}
```
6. 创建QuartzHostedService类:创建一个QuartzHostedService类,实现IHostedService接口,并在StartAsync方法中启动Scheduler。
```
public class QuartzHostedService : IHostedService
{
private readonly ISchedulerFactory _schedulerFactory;
private readonly IJobFactory _jobFactory;
private readonly IEnumerable<JobSchedule> _jobSchedules;
public QuartzHostedService(
ISchedulerFactory schedulerFactory,
IJobFactory jobFactory,
IEnumerable<JobSchedule> jobSchedules)
{
_schedulerFactory = schedulerFactory;
_jobFactory = jobFactory;
_jobSchedules = jobSchedules;
}
public IScheduler Scheduler { get; set; }
public async Task StartAsync(CancellationToken cancellationToken)
{
Scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
Scheduler.JobFactory = _jobFactory;
foreach (var jobSchedule in _jobSchedules)
{
var job = JobBuilder.Create(jobSchedule.JobType)
.WithIdentity(jobSchedule.JobType.FullName)
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity($"{jobSchedule.JobType.FullName}.trigger")
.WithCronSchedule(jobSchedule.CronExpression)
.Build();
await Scheduler.ScheduleJob(job, trigger, cancellationToken);
}
await Scheduler.Start(cancellationToken);
}
public async Task StopAsync(CancellationToken cancellationToken)
{
await Scheduler?.Shutdown(cancellationToken);
}
}
```
现在,你已经成功地配置了Quartz,可以在MyJob类中编写你的任务逻辑了。
阅读全文