ASP.NET Core+Quartz.Net實現web定時任務

加個“星標”,每天清晨 07:25,乾貨推送!

作為一枚後端程序狗,項目實踐常遇到定時任務的工作,最容易想到的的思路就是利用Windows計劃任務/wndows service程序/Crontab程序等主機方法在主機上部署定時任務程序/腳本。

但是很多時候,使用的是共享主機或者受控主機,這些主機不允許你私自安裝exe程序、Windows服務程序。

web程序中做定時任務,目前有兩個方向:

① ASP.NET Core自帶的HostService, 這是一個輕量級的後臺服務,需要搭配timer完成定時任務②老牌Quartz.Net組件,支持複雜靈活的Scheduling、支持ADO/RAM Job任務存儲、支持集群、支持監聽、支持插件。

此處我們的項目使用稍複雜的Quartz.net實現web定時任務。

項目背景

最近需要做一個計數程序:採用redis計數,設定每小時將當日累積數據持久化到關係型數據庫sqlite。

<code>添加Quartz.Net Nuget依賴包
<packagereference>
/<code>

① 定義定時任務內容:Job

② 設置觸發條件:Trigger

③ 將Quartz.Net集成進ASP.NET Core

頭腦風暴

IScheduler類包裝了上述背景需要完成的第①②點工作,

<code>SimpleJobFactory/<code>工廠類定義了生成Job任務的過程:利用<code>反射機制/<code>調用<code>無參構造函數/<code>形成的Job實例

<code>//----------------選自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
/// 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 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(Type type)
{
if (type == )
{
throw new ArgumentException(nameof(type), "Cannot instantiate ");
}
ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);
if (ci == )
{
throw new ArgumentException("Cannot instantiate type which has no empty constructor", type.Name);
}
return (T) ci.Invoke(new object[0]);
}
/<ijob>/<code>

很多時候,定義的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是以<code>依賴注入/<code>為基礎的,利用ASP.NET Core內置依賴注入容器IServiceProvider管理Job的實例化依賴

編碼實踐

已經定義好Job類:UsageCounterSyncJob

  1. 自定義Job工廠類:IOCJobFactory

<code> /// <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)
{
}
}
/<code>
  1. 在Quartz啟動過程中應用自定義Job工廠

<code> 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 == )
{
return;
}
if (_scheduler.Shutdown(waitForJobsToComplete: true).Wait(30000))
_scheduler = ;
else
{
}
_logger.LogCritical("Schedule job upload as application stopped");

}
}
/<usagecountersyncjob>/<quartzstartup>/<code>
  1. 結合ASP.NET Core依賴注入;web啟動時綁定Quartz.Net

<code>//-------------------------------截取自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);
}
/<quartzstartup>/<quartzstartup>/<usagecountersyncjob>/<code>

以上: 我們對接ASP.NET Core依賴注入框架實現了一個自定義的JobFactory,每次任務觸發時創建瞬時Job.

Github地址:https://github.com/zaozaoniao/ASPNETCore-Quartz.NET.git

附:IIS網站低頻訪問導致工作進程進入閒置狀態的解決辦法

IIS為網站默認設定了20min閒置超時時間:20分鐘內沒有處理請求、也沒有收到新的請求,工作進程就進入閒置狀態。

IIS上低頻web訪問會造成工作進程關閉,此時應用程序池回收,Timer等線程資源會被銷燬;當工作進程重新運作,Timer可能會重新生成, 但我們的設定的定時Job可能沒有按需正確執行。

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

故為IIS站點實現低頻web訪問下的定時任務:

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


分享到:


相關文章: