Quartz .Net 配置以及Job使用依赖注入

使用扩展函数的方式在“Util”中进行配置,在 WebHost/Host 中进行使用。

  • Util中的配置操作
    • 在Host中进行使用
      • Host中的 DefaultJobFactory 以及 QuartzJob

Util中的配置操作

public static IServiceCollection ConfigureQuartz(this IServiceCollection collection, List<Type> jobs,
            IJobFactory jobFactory)
{
     LogProvider.SetCurrentLogProvider(new ConsoleLogProvider());
     var scheduler = new StdSchedulerFactory().GetScheduler().GetAwaiter().GetResult();
     scheduler.JobFactory = jobFactory;
     scheduler.Start();
     var trigger = TriggerBuilder.Create()
         .WithIdentity("bg_trigger", "bg_group")
         .StartNow()
         .WithSimpleSchedule(x => x
             .WithIntervalInSeconds(10)
             .RepeatForever())
         .Build();
     jobs.ForEach(z =>
     {
         var job = JobBuilder.Create(z)
             .Build();
         scheduler.ScheduleJob(job, trigger);
     });
     return collection;
 }

        private class ConsoleLogProvider : ILogProvider
        {
            public Logger GetLogger(string name)
            {
                return (level, func, exception, parameters) =>
                {
                    if (level >= LogLevel.Info && func != null)
                    {
                        Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] [" + level + "] " + func(),
                            parameters);
                    }

                    return true;
                };
            }

            public IDisposable OpenNestedContext(string message)
            {
                throw new NotImplementedException();
            }

            public IDisposable OpenMappedContext(string key, object value, bool destructure = false)
            {
                throw new NotImplementedException();
            }
        }

在Host中进行使用

ConfigureServices((hostContext, services) =>
{
    services.ConfigureQuartz(new List<Type>() {typeof(QuartzJob)},
        new DefaultJobFactory(services.BuildServiceProvider()));
})

Host中的 DefaultJobFactory 以及 QuartzJob

  • DefaultJobFactory
public class DefaultJobFactory : IJobFactory
{
    public DefaultJobFactory(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    private readonly IServiceProvider _serviceProvider;

    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        var jobType = bundle.JobDetail.JobType;

        return _serviceProvider.GetService(jobType) as IJob;
    }

    public void ReturnJob(IJob job)
    {
        var disposable = job as IDisposable;
        disposable?.Dispose();
    }
}
  • QuartzJob
public class QuartzJob : IJob
{
 
    public QuartzJob(ISyncBusiness syncBusiness)
    {
        _syncBusiness = syncBusiness;
    }
	// Using DI in Job Class
    private readonly ISyncBusiness _syncBusiness;
    
    public async Task Execute(IJobExecutionContext context)
    {
        await _syncBusiness.DoSomething();
    }
}

你可能感兴趣的:(.Net,Core,c#)