.Net Core Quartz

Quartz介绍

Quartz主要有三部分组成任务(Job)、触发器(Trigger)和调度器(Schedule)。

开发环境:VS2019、.Net5、Quartz.AspNetCore 3.6.2

1、引入Quartz.AspNetCore

.Net Core Quartz_第1张图片

2、创建TaskJob.cs文件

[DisallowConcurrentExecution]
    public class TaskJob : IJob
    {
        public System.Threading.Tasks.Task Execute(IJobExecutionContext context)
        {
            LogHelper.Info("======TaskJob:Call-Start======");

            LogHelper.Info("定时任务测试成功");

            LogHelper.Info("======TaskJob:Call-End======");
            return System.Threading.Tasks.Task.CompletedTask;
        }
    }

3、修改Startup.cs文件中ConfigureServices方法

public void ConfigureServices(IServiceCollection services)
        {
            services.AddQuartz(q => {
                q.UseMicrosoftDependencyInjectionJobFactory();
                var jobKey = new JobKey("MyJob");
                q.AddJob(opts => opts.WithIdentity(jobKey));
                q.AddTrigger(tri => 
                tri.ForJob(jobKey)
                .WithIdentity("MyJob-trigger")
                .WithCronSchedule(Configuration.GetConnectionString("QuartzExecutionTime")));
            });
            services.AddQuartzHostedService(q =>q.WaitForJobsToComplete = true);

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "FescoFast.Collect.Api", Version = "v1" });
            });
        }

4、配置appsettings.json文件,设置定时任务执行时间

.Net Core Quartz_第2张图片

 完成以上操作设置好定时任务执行时间后运行项目,在日志里查看输出记录

你可能感兴趣的:(.NetCore,c#,.netcore)