ASP.NET Core+Quartz.Net实现web定时任务

加个“星标”,每天清晨 07:25,干货推送!

本文转载自公众号【Dotnet Plus】——作者【小码甲】

作为一枚后端程序狗,项目实践常遇到定时任务的工作,最容易想到的的思路就是利用Windows计^ = W |划任务/wndows service程序/Crontab程序等主机方法在主机上部署定时任务程序/脚本。

但是很多时候,使用的是共享主机或者受控主机,这些主机不允许你私自安装exe程序、Windows服务程序。

web程序中做定时任务,目前有两个方向:

① ASP.NET Core自带的HostService, 这是一个轻量级的后台服务,需要搭配timer完成定时任务②老牌Quartz.Netu { ? L 4 & ` W ^组件,支持复杂灵活的Scheduling、支持ADO/RAM Job任务存储、支持集群、支持监听、支持插件。

此处我们的项目使用g + = S稍复杂的Quartz.net实现web定时任务。

项目背景

最近需: } I U C = y q要做一个计数程序:采用redis计数,设定每小时将当日累积数据持久化到关系型数据库sqlite。

添加Quartz.Net Nuget依赖包
<PaE l hckageReference Include=\"QuartzO H @ ] # ( q T\" Version=\"3.0.6\" />

① 定义定时任务内容:Joc 9 U M 6 Z ` 8 hb

设置F N a 3 , A = 4 M触发条件:Trigger

③ 将Quar, p U C * D E }tz.Netq ) d H % S w ` ;集成进ASP.NET Core

头脑风暴

IScheduler= _ 2类包装了上述背景需要完成的第①②点工作,

SimpleJobFactory工厂类定义了生成Je n oob任G j X v k务的过程:利用反射机制调用无参构造H 6 7 6 A A函数形成的Job实例

//----------------选自Quartz.Simpl.SimpleJobFactory类-------------
using System;
us2 i o & ? (ing Quartz.Logging;
using Quartz.Spi;
using Q8 R o l ^ c Iuartz.Util;
namespace Quartz.Simpl
{
/// <summary>
/// The default JobFactory used by Quartz - simply calls
/// <see cref=\"ObjectUtils.InstantiateTyQ 9 h @pe{T}\" /> on the job class.
/// </summary>
public cl! w 6 & X B O 0asa X 3 ; q 3 *s SimpleJobFactom 8 kry : IJobFactory
{
private static readonly ILog log = LogProvider.GetLogger(typeof (SimpleJobFacU ] e O 2 X | *tory));

/// <summary>
/// Called by the scheduler at the time of the trigger firing, in order to
/// pA } Z Y =roduce aJ = 0 G <see cref=\"IJoz V ib\" /> instance on which to call Execute.
/// </summary>

publ8 6 ric virtual IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
IJobDetail jobDetail = bundle.JobDetail;
Type jobType = jobDetao ! 0 # k - Oil.JobType;
try
{
if (log.IsDebugEnabled)
{
log.Debug($\"Producing instance of Job \'n 3 G{jobDetail.Key}\', class={jobTA L Cype.FullName}\");
}

return ObjectUtils.InstantiateType<IJob>(jobType);
}
catch (Exception e)
{
SchedulerException se = new SchedulerException($\"Problem instantiating class \'{jobDetail.JobType.FullName}\'\", e);
throw se;
}
}

///D @ v R L 9 <summary>
/// Allows the job factory to destroy/cleanup the job if needed.
/// No-opS : J ~ P q U when using S7 K & :impleJobFactor, e H Dy.# D V I 1
/// </summary&K U U v i W 7gt;
public virtual vn & G A Y %oid ReturnW W # z Y R Z Q ]Job(IJob job)
{
var dispos* { 3 zable = job as IDisposy G ` @able;
disposable?.Dispose;
}
}
}

//------------------节选自Quartz.Util.ObjeV o )ctUtils类-------------------------
public static T InstantiateType~ C ] b Q 0 O J s<T>(Type type)
{
if (typet } t == )
{
throw new ArgumentException(nameof(type),/ ^ H x 5 O t - \"Cannot instantiate \");
}
ConstructorInfo cv A # |i = type.GetConstructor(Type.EmptyTypes);
if (ci == )
{
throw new Argumentz r I D - T 3 @ jException(\"CannotW M A } 5 ) instantiate type which has no empty constructor\", type.Name);
}
return (T) ci.I+ 5 # B m 4 5nvoke(new object[0]);
}) A q 2 A % T r L

很多时候,定义的Job任务依赖了其他服务(该Job定义有参构造函数),此时默认的SimpleJobF! c k $ m _ V : {actory不能满足实例化要求,考虑自定义Job工厂类

c b LO U 1 #思路:① Quartz.Net提供IJobFactory接口M @ +,以便开发者定义灵活的Job工厂类

JobFactories may be of use to those wishing to have their application produce IJob instances via some special mechaB 3 i @ B h Pnism, such as to give the opportunity for dependency injR * jection

② ASP.NET Core是以Z @ H赖注入为基础的,利用ASP.NET Core内置依赖注入容器IServiceProvider管理Job的实例化依赖

编码实践

已经定义好Job类:UsageCounterSyncJob

  1. 自定义Job工厂类:IOCJobFactory

 /// <summary>
/// IOCJobFactory :在Time4 ` J t / ir触发的时候产生对应Job实例
/// </suh ) O 7 C x Qmmary>
public class IOCJobFactory : IJobFactory
{
protectV ] 9 e aed readonly IServiceProvider Container;

public IOCJobFactory(IServiceProvider container)
{
Container = container;
}

//Called b| D M ` Fy the scheduler at the t[ h ~ , : a 9ime of the trigger firing, in order to produce
// a Quartz.IJr # c . N s V I 5ob instance on wZ w K - g / j /hich to call8 s K Execute.
public IJob NewJob(TriggerFiredBun[ } + ~ 5dle bundle, IScheduler scheduler)
{
return Container.GetService(bundlr ( )e.JobDetail.JobTypO w W * n V fe) as IJob;
}

// Allows the job factory to des% 5 ? . x ! wtroy/cleanup the job if needed.
public void ReturnJob(IJob job)
{
}
}
  1. 在Quartz启动过程中应用自定义Job工厂

 public class QuartzStartup
{
public IScheduler _scheduler { get; set; }

private readonly ILogger _logger;
private r) , 9eadonly* j ! IJobFactory iocJobfactory;
public Qua7 V : . x )rtzStartup(IServiceProviderC _ G Q : k IocContainer, ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<QuartzSt| R ~ nartup>;
iocJobfactory = ne3 E }w IOCJob8 - _Factory(IocContainer);
va_ 2 Ur schedulerFactory = new StdSchedulerFactory;
_scheduler = schedulerFactory.GetScheduler.Result;
_scheduler.JobFactory = iocJobfactory;
}
// Quartz.Net启动后注册job和trigger
public void Start
{
_logger.LogInformation(\"Schedule job loat c L M N N qd as a: 1 @ P 5 @ @ [pplication start.\");
_scheduler.Start.Wait;

var UsageCounterSyncJy C g W u K M Uob = JobBuilder.Create<UsageCounterSyncJob>
.WithId? M u b { r = ! @entity(\"UsageCounterSyncJob\")
.Build;

var UsageCounterSyncJobTriq } (gger = TriggerBuilder.Create
.WithIdentity(\"UsageCS 0 ~ . # *ounterSyncCron0 U . +\")
.StartN- 5 l - r Yow
.WithCronSchedule(\ 0 V d {"0 0 * * * ?\") // Seconds,Minutes,Hours,Day-of-Month,Month,{ + r VDay-of-Week,Yex Y | Kar(optional field)
.Build;
_schedul1 h ^ p C % g & 8er.ScheduleJob(Usa| @ y 0 ( u BgeCouny B s b + VterSyncJob, UsageCounterSyl 8 N & ncJobTrigger).Wait;

_scheduler.TriggerJob(new JobKey(\"UsageCounterSyncJoc + r U +bb _ u k & }\"));
}

public void Stop
{
if (_scheduler == )
{
return;
}
if (_scheduler.Shut) # o * 8 t F Hdown(waitForJobsToComplete: true).Wait(30000))
_scheduler = ;
else
{
}
_8 V E $ P W B Elogger.LogCriticalf K m(} ` 1\"Schedule job upload as application sto% i 8 O q t $ }pped\");
}
}
  1. 结合ASP.NET Core依赖注入;( P t z 4web启动时绑定Quartz.Net

/ F y | U T Q/------ { 1----------------g ( `--s 2 I #--------截i B ` h n取自Startup文件----------------------n N t B f }--
......
services.AddTransient<UsageCounterSyncJobO o 8 1 N>; // 这里使用瞬时依赖注入
services.AddSingleton<QuartzStartup>;
......

// 绑定Quartz.Net
public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.I! % ^ n }ApplicationLi; ? I zfetime lifetime, ILoggerFactory loggerFactory)
{
var quartz = app.ApplicationServices.GetRequiredServL O d p b { S ?ice<QuartzStl d @ j T F : ,artup>;
lifetime.ApplicationStarted.Register(quartz.Start);
lifQ r [ m etime.ApplicationStopped.Register(quarH # 6 %tz.StopN z m G R);
}

以上: 我们对接ASP.NET Core依赖注入框架实现了一个自定义的J- | ; 9 HobFacto4 9 O . hry,每次任务触i X _ P A发时创建瞬时Job.

Github地址:https://github.com/zaozaoniao/ASPNETCore-Quartz.NET.gi? ) - H s -t

附:IIS网站低频访问导致工作进程进入闲置状态的解决办法

IIS为网h ` 8站默Z n 4认设定了20min闲置超时时间:20分钟内没有处理请求、也没有收到新的请求,工作进程就进入闲置状态。

IIS上低频web访问会造成工作进程关闭,此时应用程序池~ 8 (回收,Timer等线程资源会被销毁;当工作进程重新运作,Timer可能会重新生成, 但我们的设定W f r } z F *的定时Job可能没有按需正确执行。

ASP.NET Core+Quartz.Net实现web定时任务

故为IIS站点实现低频web访问下的定时任务:

ASP.NET Core+Quartz.Net实现web定时任务

上一篇

中科创达:公司已开展数字钱包、硬件级数据认证等区块链相关业务

下一篇

阿里“新灯塔”评测体系升级 10万中小商家成为金牌卖家

评论已经被关闭。

插入图片
返回顶部