//----------------選自Quartz.Simpl.SimpleJobFactory類-------------
using System;
using Quartz.Logging;
using Quartz.Spi;
using Quartz.Util;
namespace Quartz.Simpl
{/// <summary>/// The default JobFactory used by Quartz - simply calls/// <see cref="ObjectUtils.InstantiateType{T}" /> on the job class./// </summary>public class SimpleJobFactory : IJobFactory{private static readonly ILog log = LogProvider.GetLogger(typeof (SimpleJobFactory));/// <summary>/// Called by the scheduler at the time of the trigger firing, in order to/// produce a <see cref="IJob" /> instance on which to call Execute./// </summary>public virtual IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler){IJobDetail jobDetail = bundle.JobDetail;Type jobType = jobDetail.JobType;try{if (log.IsDebugEnabled()){log.Debug($"Producing instance of Job '{jobDetail.Key}', class={jobType.FullName}");}return ObjectUtils.InstantiateType<IJob>(jobType);}catch (Exception e){SchedulerException se = new SchedulerException($"Problem instantiating class '{jobDetail.JobType.FullName}'", e);throw se;}}/// <summary>/// Allows the job factory to destroy/cleanup the job if needed./// No-op when using SimpleJobFactory./// </summary>public virtual void ReturnJob(IJob job){var disposable = job as IDisposable;disposable?.Dispose();}}
}//------------------節選自Quartz.Util.ObjectUtils類-------------------------public static T InstantiateType<T>(Type type)
{if (type == null){throw new ArgumentNullException(nameof(type), "Cannot instantiate null");}ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);if (ci == null){throw new ArgumentException("Cannot instantiate type which has no empty constructor", type.Name);}return (T) ci.Invoke(new object[0]);
}
關鍵思路: ① Quartz.Net提供IJobFactory接口,以便開發者定義靈活的Job工廠類
JobFactories may be of use to those wishing to have their application produce IJob instances via some special mechanism, such as to give the opportunity for dependency injection
② ASP.NET Core是以依賴注入為基礎的,利用ASP.NET Core內置依賴注入容器IServiceProvider管理Job的實例化依賴
編碼實踐
已經定義好Job類:UsageCounterSyncJob
自定義Job工廠類:IOCJobFactory
/// <summary>/// IOCJobFactory :在Timer觸發的時候產生對應Job實例/// </summary>public class IOCJobFactory : IJobFactory{protected readonly IServiceProvider Container;public IOCJobFactory(IServiceProvider container){Container = container;}//Called by the scheduler at the time of the trigger firing, in order to produce// a Quartz.IJob instance on which to call Execute.public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler){return Container.GetService(bundle.JobDetail.JobType) as IJob;}// Allows the job factory to destroy/cleanup the job if needed.public void ReturnJob(IJob job){}}