AspNet Core上实现web定时任务实例(2)

// -------每小时将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可能没有按需正确执行。

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

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

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

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdsdww.html