① ASP.NET Core自帶的HostService, 這是一個(gè)輕量級(jí)的后臺(tái)服務(wù),需要搭配timer完成定時(shí)任務(wù) ②老牌Quartz.Net組件,支持復(fù)雜靈活的Scheduling、支持ADO/RAM Job任務(wù)存儲(chǔ)、支持集群、支持監(jiān)聽、支持插件。
//----------------選自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();}}
}//------------------節(jié)選自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]);
}
關(guān)鍵思路: ① Quartz.Net提供IJobFactory接口,以便開發(fā)者定義靈活的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是以依賴注入為基礎(chǔ)的,利用ASP.NET Core內(nèi)置依賴注入容器IServiceProvider管理Job的實(shí)例化依賴
編碼實(shí)踐
已經(jīng)定義好Job類:UsageCounterSyncJob
自定義Job工廠類:IOCJobFactory
/// <summary>/// IOCJobFactory :在Timer觸發(fā)的時(shí)候產(chǎn)生對(duì)應(yīng)Job實(shí)例/// </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){}}