How to start Quartz in ASP.NET Core?

后端 未结 5 1393
你的背包
你的背包 2020-12-02 07:00

I have the following class

 public class MyEmailService
 {
    public async Task SendAdminEmails()
    {
        ...
    }
    public async Task&         


        
5条回答
  •  一个人的身影
    2020-12-02 07:17

    What code do I need to schedule these methods using Quartz in ASP.NET Core? I also need to know how to start Quartz in ASP.NET Core as all code samples on the internet still refer to previous versions of ASP.NET.

    Hi, there is now a good quartz DI to initialize and use

    [DisallowConcurrentExecution]
    public class Job1 : IJob
    {
        private readonly ILogger _logger;
    
        public Job1(ILogger logger)
        {
            _logger = logger;
        }
    
        public async Task Execute(IJobExecutionContext context)
        {
            _logger.LogInformation("Start job1");
            await Task.Delay(2, context.CancellationToken);
            _logger?.LogInformation("End job1");
        }
    }
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
    
            services.AddQuartz(cfg =>
            {
                cfg.UseMicrosoftDependencyInjectionJobFactory(opt =>
                {
                    opt.AllowDefaultConstructor = false;
                });
    
                cfg.AddJob(jobCfg =>
                {
                    jobCfg.WithIdentity("job1");
                });
    
                cfg.AddTrigger(trigger =>
                {
                    trigger
                        .ForJob("job1")
                        .WithIdentity("trigger1")
                        .WithSimpleSchedule(x => x
                            .WithIntervalInSeconds(10)
                            .RepeatForever());
                });
            });
    
            services.AddQuartzHostedService(opt =>
            {
                opt.WaitForJobsToComplete = true;
            });
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // standart impl
        }
    }
    

提交回复
热议问题