作为一枚后端程序狗,项目实践常遇到定时任务的工作,最容易想到的的思路就是利用Windows计划任务/wndows service程序/Crontab程序等主机方法在主机上部署定时任务程序/脚本。
但是很多时候,使用的是共享主机或者受控主机,这些主机不允许你私自安装exe程序、Windows服务程序。
web程序中做定时任务,目前有两个方向:
① ASP.NET Core自带的HostService, 这是一个轻量级的后台服务,需要搭配timer完成定时任务
②老牌Quartz.Net组件,支持复杂灵活的Scheduling、支持ADO/RAM Job任务存储、支持集群、支持监听、支持插件。
此处我们的项目使用稍复杂的Quartz.net实现web定时任务。
项目背景
最近需要做一个计数程序:采用redis计数,设定每小时将当日累积数据持久化到关系型数据库sqlite。
添加Quartz.Net Nuget依赖包 <PackageReference Include="Quartz" Version="3.0.6" />
① 定义定时任务内容:Job
② 设置触发条件:Trigger
③ 将Quartz.Net集成进ASP.NET Core
头脑风暴
IScheduler类包装了上述背景需要完成的第①②点工作,
SimpleJobFactory
工厂类定义了生成Job任务的过程:利用反射机制
调用无参构造函数
形成的Job实例
//----------------选自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]); }
很多时候,定义的Job任务依赖了其他服务(该Job定义有参构造函数),此时默认的SimpleJobFactory不能满足实例化要求,考虑自定义Job工厂类。
关键思路:
① 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) { } }
- 在Quartz启动过程中应用自定义Job工厂
public class QuartzStartup { public IScheduler _scheduler { get; set; } private readonly ILogger _logger; private readonly IJobFactory iocJobfactory; public QuartzStartup(IServiceProvider IocContainer, ILoggerFactory loggerFactory) { _logger = loggerFactory.CreateLogger<QuartzStartup>(); iocJobfactory = new IOCJobFactory(IocContainer); var schedulerFactory = new StdSchedulerFactory(); _scheduler = schedulerFactory.GetScheduler().Result; _scheduler.JobFactory = iocJobfactory; } // Quartz.Net启动后注册job和trigger public void Start() { _logger.LogInformation("Schedule job load as application start."); _scheduler.Start().Wait(); var UsageCounterSyncJob = JobBuilder.Create<UsageCounterSyncJob>() .WithIdentity("UsageCounterSyncJob") .Build(); var UsageCounterSyncJobTrigger = TriggerBuilder.Create() .WithIdentity("UsageCounterSyncCron") .StartNow() .WithCronSchedule("0 0 * * * ?") // Seconds,Minutes,Hours,Day-of-Month,Month,Day-of-Week,Year(optional field) .Build(); _scheduler.ScheduleJob(UsageCounterSyncJob, UsageCounterSyncJobTrigger).Wait(); _scheduler.TriggerJob(new JobKey("UsageCounterSyncJob")); } public void Stop() { if (_scheduler == null) { return; } if (_scheduler.Shutdown(waitForJobsToComplete: true).Wait(30000)) _scheduler = null; else { } _logger.LogCritical("Schedule job upload as application stopped"); } }
- 结合ASP.NET Core依赖注入;web启动时绑定Quartz.Net
//-------------------------------截取自Startup文件------------------------ ...... services.AddTransient<UsageCounterSyncJob>(); // 这里使用瞬时依赖注入 services.AddSingleton<QuartzStartup>(); ...... // 绑定Quartz.Net public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IApplicationLifetime lifetime, ILoggerFactory loggerFactory) { var quartz = app.ApplicationServices.GetRequiredService<QuartzStartup>(); lifetime.ApplicationStarted.Register(quartz.Start); lifetime.ApplicationStopped.Register(quartz.Stop); }
以上: 我们对接ASP.NET Core依赖注入框架实现了一个自定义的JobFactory,每次任务触发时创建瞬时Job.
Github地址:https://github.com/zaozaoniao/ASPNETCore-Quartz.NET.git
附:IIS网站低频访问导致工作进程进入闲置状态的解决办法
IIS为网站默认设定了20min闲置超时时间:20分钟内没有处理请求、也没有收到新的请求,工作进程就进入闲置状态。
IIS上低频web访问会造成工作进程关闭,此时应用程序池回收,Timer等线程资源会被销毁;
当工作进程重新运作,Timer可能会重新生成, 但我们的设定的定时Job可能没有按需正确执行。
故为IIS站点实现低频web访问下的定时任务:可设置IdleTimeOut =0;将[应用程序池]->[正在回收]->不勾选[回收条件]