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

原文:ASP.NET Core2.2+Quartz.Net 实现web定时任务

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

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

码甲会想到在web程序中做定时任务, 目前有两个方向:

①.AspNetCore自带的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集成进AspNet 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>
    /// <seealso cref="IJobFactory" />
    /// <seealso cref="PropertySettingJobFactory" />
    /// <author>James House</author>
    /// <author>Marko Lahma (.NET)</author>
    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>
        /// <remarks>
        /// It should be extremely rare for this method to throw an exception -
        /// basically only the case where there is no way at all to instantiate
        /// and prepare the Job for execution.  When the exception is thrown, the
        /// Scheduler will move all triggers associated with the Job into the
        /// <see cref="TriggerState.Error" /> state, which will require human
        /// intervention (e.g. an application restart after fixing whatever
        /// configuration problem led to the issue with instantiating the Job).
        /// </remarks>
        /// <param name="bundle">The TriggerFiredBundle from which the <see cref="IJobDetail" />
        ///   and other info relating to the trigger firing can be obtained.</param>
        /// <param name="scheduler"></param>
        /// <returns>the newly instantiated Job</returns>
        /// <throws>  SchedulerException if there is a problem instantiating the Job. </throws>
        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任务作为依赖注入组件,加入依赖注入容器。

关键思路:

①  IScheduler 开放了JobFactory 属性,便于你控制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

② AspNet Core的服务架构是以依赖注入为基础的,利用ASPNET Core已有的依赖注入容器IServiceProvider管理Job任务的创建过程。

编码实践

① 定义Job内容:

// -------每小时将redis数据持久化到sqlite, 每日凌晨跳针,持久化昨天全天数据---------------------
public class UsageCounterSyncJob : IJob
{
        private readonly EqidDbContext _context;
        private readonly IDatabase _redisDB1;
        private readonly ILogger _logger;
        public UsageCounterSyncJob(EqidDbContext context, RedisDatabase redisCache, ILoggerFactory loggerFactory)
        {
            _context = context;
            _redisDB1 = redisCache[1];
            _logger = loggerFactory.CreateLogger<UsageCounterSyncJob>();
        }
         public async Task Execute(IJobExecutionContext context)
        {
            // 触发时间在凌晨,则同步昨天的计数
            var _day = DateTime.Now.ToString("yyyyMMdd");
            if (context.FireTimeUtc.LocalDateTime.Hour == 0)
                _day = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");

            await SyncRedisCounter(_day);
            _logger.LogInformation("[UsageCounterSyncJob] Schedule job executed.");
        }
        ......
 }

②注册Job和Trigger:

namespace EqidManager
{
    using IOCContainer = IServiceProvider;
    // Quartz.Net启动后注册job和trigger
    public class QuartzStartup
    {
        public IScheduler _scheduler { get; set; }

        private readonly ILogger _logger;
        private readonly IJobFactory iocJobfactory;
        public QuartzStartup(IOCContainer IocContainer, ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<QuartzStartup>();
            iocJobfactory = new IOCJobFactory(IocContainer);
            var schedulerFactory = new StdSchedulerFactory();
            _scheduler = schedulerFactory.GetScheduler().Result;
            _scheduler.JobFactory = iocJobfactory;
        }

        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");
        }
    }

    /// <summary>
    /// IOCJobFactory :实现在Timer触发的时候注入生成对应的Job组件
    /// </summary>
    public class IOCJobFactory : IJobFactory
    {
        protected readonly IOCContainer Container;

        public IOCJobFactory(IOCContainer 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)
        {
        }
    }
}

③结合AspNet Core 注入组件;绑定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);
}

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

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

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

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

设置Idle TimeOut =0;同时将【应用程序池】->【正在回收】->不勾选【回收条件】

更多资料请参考:  https://blogs.technet.microsoft.com/erezs_iis_blog/2013/06/26/new-feature-in-iis-8-5-idle-worker-process-page-out/

原文地址:https://www.cnblogs.com/lonelyxmas/p/10646669.html

时间: 2024-08-01 08:54:31

ASP.NET Core2.2+Quartz.Net 实现web定时任务的相关文章

ASP.NET Core2基于RabbitMQ对Web前端实现推送功能

在我们很多的Web应用中会遇到需要从后端将指定的数据或消息实时推送到前端,通常的做法是前端写个脚本定时到后端获取,或者借助WebSocket技术实现前后端实时通讯.因定时刷新的方法弊端很多(已不再采用),所以基于WebSocket技术实现的通讯方案正越来越受大家喜爱,于是在ASP.NET中就有了鼎鼎大名的Signalr.但Signalr不是咱们这里的主角,这里将给大家介绍另一套基于WebSocket的前后端通讯方案,可以给大家在应用中多一个选择. 准备 在开始动手前,咱们先简单介绍下方案的组成部

深度理解IIS下部署ASP.NET Core2.1 Web应用拓扑图

原文:深度理解IIS下部署ASP.NET Core2.1 Web应用拓扑图 IIS部署ASP.NET Core2.1 应用拓扑图 我们看到相比Asp.Net, 出现了3个新的组件:ASP.NET Core Module.Kestrel.dotnet.exe, 后面我们会理清楚这三个组件的作用和组件之间的交互原理. 引入Kestrel的原因 进程内HTTP服务器,与老牌web服务器解耦,实现跨平台部署 IIS.Nginx.Apache等老牌web服务器有他们自己的启动进程和环境:为了实现跨平台部署

一步一步带你做WebApi迁移ASP.NET Core2.0

随着ASP.NET Core 2.0发布之后,原先运行在Windows IIS中的ASP.NET WebApi站点,就可以跨平台运行在Linux中.我们有必要先说一下ASP.NET Core. ASP.NET Core 是新一代的 ASP.NET,第一次出现时的代号为 ASP.NET vNext,后来命名为ASP.NET 5,随着它的完善与成熟,最终命名为 ASP.NET Core,这表明它已不是 ASP.NET 的升级,而是一个重新设计的Web开发框架.而它一个非常重要的变化就是它不再依赖于I

centos7.x docker 跑asp.net core2.x项目

windows内: 做一个vs2017(15.8版本)新建.net core项目 asp.net core web应用程序api项目模板 asp.net core2.1 不选docker支持(因为在windows下配docker支持非常麻烦) https开着,不过默认发布到linux的时候最后好像都是http: 新建得项目WebApplication1,调试的话 https://localhost:5001/api/values会返回一个json文件内容是 ["value1",&quo

asp.net core2.0 部署centos7/linux系统 --守护进程supervisor(二)

原文:asp.net core2.0 部署centos7/linux系统 --守护进程supervisor(二) 续上一篇文章:asp.net core2.0 部署centos7/linux系统 --安装部署(一),遗留的问题而来,对程序添加守护进程,使网站可以持续化的运行起来. ? 1.介绍supervisor ?? ?Supervisor(http://supervisord.org/)是用Python开发的一个client/server服务,是Linux/Unix系统下的一个进程管理工具,

将asp.net core2.0项目部署在IIS上运行

原文:将asp.net core2.0项目部署在IIS上运行 前言: ?与ASP.NET时代不同,ASP.NET Core不再是由IIS工作进程(w3wp.exe)托管,而是独立运行的.它独立运行在控制台应用程序中,并通过dotnet运行时命令调用.它并没有被加载到IIS工作进程中,但是IIS却加载了名为AspNetCoreModule的本地Module,这个Module用于执行外部的控制台程序. ?部署之前要确保你的IIS上已经安装了AspNetCoreModule托管模块,如果没有的话,点击

[ASP.NET MVC 小牛之路]18 - Web API

原文:[ASP.NET MVC 小牛之路]18 - Web API Web API 是ASP.NET平台新加的一个特性,它可以简单快速地创建Web服务为HTTP客户端提供API.Web API 使用的基础库是和一般的MVC框架一样的,但Web API并不是MVC框架的一部分,微软把Web API相关的类从 System.Web.Mvc 命名空间下提取了出来放在 System.Web.Http 命名空间下.这种理念是把 Web API 作为ASP.NET 平台的核心之一,以使Web API能使用在

Go语言和ASP.NET的一般处理程序在处理WEB请求时的速度比较

Go语言和ASP.NET的一般处理程序在处理WEB请求时的速度比较 1.首先写一个Go语言的简单WEB程序,就返回一个HelloWord! package main import ( f "fmt" "log" "net/http" // "strings" ) func sayhelloName(w http.ResponseWriter, r *http.Request) { // r.ParseForm() // f.P

来篇文章:ASP。NET程序中动态修改web.config中的设置项目 (后台CS代码)

朋友们可以自行测试,我这里都没有问题了,鳖了一上午的问题总算解决了 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; usi