当前位置:Gxlcms > asp.net > AspNet Core上实现web定时任务实例

AspNet Core上实现web定时任务实例

时间:2021-07-01 10:21:17 帮助过:73人阅读

作为一枚后端程序狗,项目实践常遇到定时任务的工作,最容易想到的的思路就是利用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实例。下面是源码:

  1. //----------------选自Quartz.Simpl.SimpleJobFactory类-------------
  2. using System;
  3. using Quartz.Logging;
  4. using Quartz.Spi;
  5. using Quartz.Util;
  6. namespace Quartz.Simpl
  7. {
  8. /// <summary>
  9. /// The default JobFactory used by Quartz - simply calls
  10. /// <see cref="ObjectUtils.InstantiateType{T}" /> on the job class.
  11. /// </summary>
  12. /// <seealso cref="IJobFactory" />
  13. /// <seealso cref="PropertySettingJobFactory" />
  14. /// <author>James House</author>
  15. /// <author>Marko Lahma (.NET)</author>
  16. public class SimpleJobFactory : IJobFactory
  17. {
  18. private static readonly ILog log = LogProvider.GetLogger(typeof (SimpleJobFactory));
  19. /// <summary>
  20. /// Called by the scheduler at the time of the trigger firing, in order to
  21. /// produce a <see cref="IJob" /> instance on which to call Execute.
  22. /// </summary>
  23. /// <remarks>
  24. /// It should be extremely rare for this method to throw an exception -
  25. /// basically only the case where there is no way at all to instantiate
  26. /// and prepare the Job for execution. When the exception is thrown, the
  27. /// Scheduler will move all triggers associated with the Job into the
  28. /// <see cref="TriggerState.Error" /> state, which will require human
  29. /// intervention (e.g. an application restart after fixing whatever
  30. /// configuration problem led to the issue with instantiating the Job).
  31. /// </remarks>
  32. /// <param name="bundle">The TriggerFiredBundle from which the <see cref="IJobDetail" />
  33. /// and other info relating to the trigger firing can be obtained.</param>
  34. /// <param name="scheduler"></param>
  35. /// <returns>the newly instantiated Job</returns>
  36. /// <throws> SchedulerException if there is a problem instantiating the Job. </throws>
  37. public virtual IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
  38. {
  39. IJobDetail jobDetail = bundle.JobDetail;
  40. Type jobType = jobDetail.JobType;
  41. try
  42. {
  43. if (log.IsDebugEnabled())
  44. {
  45. log.Debug($"Producing instance of Job '{jobDetail.Key}', class={jobType.FullName}");
  46. }
  47. return ObjectUtils.InstantiateType<IJob>(jobType);
  48. }
  49. catch (Exception e)
  50. {
  51. SchedulerException se = new SchedulerException($"Problem instantiating class '{jobDetail.JobType.FullName}'", e);
  52. throw se;
  53. }
  54. }
  55. /// <summary>
  56. /// Allows the job factory to destroy/cleanup the job if needed.
  57. /// No-op when using SimpleJobFactory.
  58. /// </summary>
  59. public virtual void ReturnJob(IJob job)
  60. {
  61. var disposable = job as IDisposable;
  62. disposable?.Dispose();
  63. }
  64. }
  65. }
  66. //------------------节选自Quartz.Util.ObjectUtils类-------------------------
  67. public static T InstantiateType<T>(Type type)
  68. {
  69. if (type == null)
  70. {
  71. throw new ArgumentNullException(nameof(type), "Cannot instantiate null");
  72. }
  73. ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);
  74. if (ci == null)
  75. {
  76. throw new ArgumentException("Cannot instantiate type which has no empty constructor", type.Name);
  77. }
  78. return (T) ci.Invoke(new object[0]);
  79. }

很多时候,定义的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内容:

  1. // -------每小时将redis数据持久化到sqlite, 每日凌晨跳针,持久化昨天全天数据---------------------
  2. public class UsageCounterSyncJob : IJob
  3. {
  4. private readonly EqidDbContext _context;
  5. private readonly IDatabase _redisDB1;
  6. private readonly ILogger _logger;
  7. public UsageCounterSyncJob(EqidDbContext context, RedisDatabase redisCache, ILoggerFactory loggerFactory)
  8. {
  9. _context = context;
  10. _redisDB1 = redisCache[1];
  11. _logger = loggerFactory.CreateLogger<UsageCounterSyncJob>();
  12. }
  13. public async Task Execute(IJobExecutionContext context)
  14. {
  15. // 触发时间在凌晨,则同步昨天的计数
  16. var _day = DateTime.Now.ToString("yyyyMMdd");
  17. if (context.FireTimeUtc.LocalDateTime.Hour == 0)
  18. _day = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
  19. await SyncRedisCounter(_day);
  20. _logger.LogInformation("[UsageCounterSyncJob] Schedule job executed.");
  21. }
  22. ......
  23. }

②注册Job和Trigger:

  1. namespace EqidManager
  2. {
  3. using IOCContainer = IServiceProvider;
  4. // Quartz.Net启动后注册job和trigger
  5. public class QuartzStartup
  6. {
  7. public IScheduler _scheduler { get; set; }
  8. private readonly ILogger _logger;
  9. private readonly IJobFactory iocJobfactory;
  10. public QuartzStartup(IOCContainer IocContainer, ILoggerFactory loggerFactory)
  11. {
  12. _logger = loggerFactory.CreateLogger<QuartzStartup>();
  13. iocJobfactory = new IOCJobFactory(IocContainer);
  14. var schedulerFactory = new StdSchedulerFactory();
  15. _scheduler = schedulerFactory.GetScheduler().Result;
  16. _scheduler.JobFactory = iocJobfactory;
  17. }
  18. public void Start()
  19. {
  20. _logger.LogInformation("Schedule job load as application start.");
  21. _scheduler.Start().Wait();
  22. var UsageCounterSyncJob = JobBuilder.Create<UsageCounterSyncJob>()
  23. .WithIdentity("UsageCounterSyncJob")
  24. .Build();
  25. var UsageCounterSyncJobTrigger = TriggerBuilder.Create()
  26. .WithIdentity("UsageCounterSyncCron")
  27. .StartNow()
  28. // 每隔一小时同步一次
  29. .WithCronSchedule("0 0 * * * ?") // Seconds,Minutes,Hours,Day-of-Month,Month,Day-of-Week,Year(optional field)
  30. .Build();
  31. _scheduler.ScheduleJob(UsageCounterSyncJob, UsageCounterSyncJobTrigger).Wait();
  32. _scheduler.TriggerJob(new JobKey("UsageCounterSyncJob"));
  33. }
  34. public void Stop()
  35. {
  36. if (_scheduler == null)
  37. {
  38. return;
  39. }
  40. if (_scheduler.Shutdown(waitForJobsToComplete: true).Wait(30000))
  41. _scheduler = null;
  42. else
  43. {
  44. }
  45. _logger.LogCritical("Schedule job upload as application stopped");
  46. }
  47. }
  48. /// <summary>
  49. /// IOCJobFactory :实现在Timer触发的时候注入生成对应的Job组件
  50. /// </summary>
  51. public class IOCJobFactory : IJobFactory
  52. {
  53. protected readonly IOCContainer Container;
  54. public IOCJobFactory(IOCContainer container)
  55. {
  56. Container = container;
  57. }
  58. //Called by the scheduler at the time of the trigger firing, in order to produce
  59. // a Quartz.IJob instance on which to call Execute.
  60. public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
  61. {
  62. return Container.GetService(bundle.JobDetail.JobType) as IJob;
  63. }
  64. // Allows the job factory to destroy/cleanup the job if needed.
  65. public void ReturnJob(IJob job)
  66. {
  67. }
  68. }
  69. }

③结合ASpNet Core 注入组件;绑定Quartz.Net

  1. //-------------------------------截取自Startup文件------------------------
  2. ......
  3. services.AddTransient<UsageCounterSyncJob>(); // 这里使用瞬时依赖注入
  4. services.AddSingleton<QuartzStartup>();
  5. ......
  6. // 绑定Quartz.Net
  7. public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IApplicationLifetime lifetime, ILoggerFactory loggerFactory)
  8. {
  9. var quartz = app.ApplicationServices.GetRequiredService<QuartzStartup>();
  10. lifetime.ApplicationStarted.Register(quartz.Start);
  11. lifetime.ApplicationStopped.Register(quartz.Stop);
  12. }

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

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

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

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

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

人气教程排行