.net6 webapi项目使用quartz

4 篇文章 1 订阅
文章介绍了如何在.NET6WebAPI项目中集成Quartz.NET3.6.0来创建定时任务。主要步骤包括安装必要的NuGet包,配置服务,设置调度器,并通过依赖注入创建和触发作业。示例中展示了添加一个每三分钟执行一次的Job,并提供了配置选项和作业生命周期管理。
摘要由CSDN通过智能技术生成

.net6 webapi项目使用quartz做定时任务,之前已经写过文章入门了解了quartz的使用

.net6 webapi项目需要引入如下包(版本号都是3.6.0)

Install-Package Quartz
Install-Package Quartz.Extensions.Hosting
Install-Package Quartz.Extensions.DependencyInjection

然后在Program.cs中加入如下配置代码 

//quartz 定时任务
builder.Services.AddQuartz(q =>
{
    q.SchedulerId = "FactorySchedule";
    q.UseMicrosoftDependencyInjectionJobFactory();//注入
    //默认设置
    q.UseSimpleTypeLoader();
    q.UseInMemoryStore();
    q.UseDedicatedThreadPool(tp =>
    {
        tp.MaxConcurrency = 10;
    });

    // quickest way to create a job with single trigger is to use ScheduleJob
    // (requires version 3.2)
    //q.ScheduleJob<TestJob>(trigger => trigger
    //    .WithIdentity("TestJob")
    //    .StartAt(DateBuilder.EvenSecondDate(DateTimeOffset.UtcNow.AddSeconds(7)))
    //    .WithDailyTimeIntervalSchedule(x => x.WithInterval(1, IntervalUnit.Minute))
    //    .WithDescription("TestJobDescription")
    //);

    var jobKey = new JobKey("TestJob");
    q.AddJob<CaseSummaryJob>(opts => opts.WithIdentity(jobKey));
    q.AddTrigger(opts => opts
       .ForJob(jobKey)
       .WithIdentity("TestJob-trigger")
       .WithSimpleSchedule(x => x.WithIntervalInMinutes(3).RepeatForever())
       .StartNow()
   //This Cron interval can be described as "run every minute" (when second is zero)
   //.WithCronSchedule("0 * * ? * *")
   );

});

// we can use options pattern to support hooking your own configuration
// because we don't use service registration api, 
// we need to manually ensure the job is present in DI
builder.Services.AddTransient<TestJob>();
// Quartz.Extensions.Hosting allows you to fire background service that handles scheduler lifecycle
// when shutting down we want jobs to complete gracefully
builder.Services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);

参考官方文档:Quartz.NET

其他quartz介绍参考C# quartz.net 定时任务(一)_woflyoycm的博客-CSDN博客_c#定时job

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类中编写你的任务逻辑了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值