内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

怎么在AspNetCore中實(shí)現(xiàn)一個(gè)web定時(shí)任務(wù)-創(chuàng)新互聯(lián)

這篇文章將為大家詳細(xì)講解有關(guān)怎么在AspNet Core中實(shí)現(xiàn)一個(gè)web定時(shí)任務(wù),文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

創(chuàng)新互聯(lián)是一群有想法、有熱情,對(duì)互聯(lián)網(wǎng)抱有執(zhí)著信念的年輕人,愿用自己的智慧和熱情,幫助您使用好互聯(lián)網(wǎng)工具,成為您的建站英雄,成為您網(wǎng)站制作和網(wǎng)絡(luò)營(yíng)銷的“秘密武器”,專注于網(wǎng)站策劃、備案、域名申請(qǐng)、設(shè)計(jì)、后臺(tái)開(kāi)發(fā)、關(guān)鍵詞優(yōu)化排名、運(yùn)營(yíng)管理、維護(hù)服務(wù)、微信網(wǎng)站、成都做手機(jī)網(wǎng)站,網(wǎng)站上線不是大家合作的終結(jié),相反,網(wǎng)站維護(hù)才剛剛開(kāi)始,我們期待常年累月的網(wǎng)站運(yùn)行過(guò)程總著為您提供更多的支持。我們致力于解決問(wèn)題,創(chuàng)造價(jià)值,不推諉,主動(dòng)承擔(dān)。

項(xiàng)目背景


采用redis計(jì)數(shù),設(shè)定每小時(shí)將當(dāng)日累積數(shù)據(jù)持久化到關(guān)系型數(shù)據(jù)庫(kù)sqlite。

添加Quartz.Net Nuget 依賴包:<PackageReference Include="Quartz" Version="3.0.6" />


  • ①.定義定時(shí)任務(wù)內(nèi)容: Job

  • ②.設(shè)置觸發(fā)條件: Trigger

  • ③.將Quartz.Net集成進(jìn)AspNet Core

頭腦風(fēng)暴

IScheduler類包裝了上述背景需要完成的第①②點(diǎn)工作 ,SimpleJobFactory定義了生成指定的Job任務(wù)的過(guò)程,這個(gè)行為是利用反射機(jī)制調(diào)用無(wú)參構(gòu)造函數(shù)構(gòu)造出的Job實(shí)例。下面是源碼:

//----------------選自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();
  }
 }
}

//------------------節(jié)選自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]);
}

很多時(shí)候,定義的Job任務(wù)依賴了其他組件,這時(shí)默認(rèn)的SimpleJobFactory不可用, 需要考慮將Job任務(wù)作為依賴注入組件,加入依賴注入容器。

關(guān)鍵思路:

①. IScheduler 開(kāi)放了JobFactory 屬性,便于你控制Job任務(wù)的實(shí)例化方式;

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的服務(wù)架構(gòu)是以依賴注入為基礎(chǔ)的,利用AspNet Core已有的依賴注入容器IServiceProvider管理Job 服務(wù)的創(chuàng)建過(guò)程。

編碼實(shí)踐

① 定義Job內(nèi)容:

// -------每小時(shí)將redis數(shù)據(jù)持久化到sqlite, 每日凌晨跳針,持久化昨天全天數(shù)據(jù)---------------------
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)
  {
   // 觸發(fā)時(shí)間在凌晨,則同步昨天的計(jì)數(shù)
   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.");
  }
  ......
 }

②注冊(cè)Job和Trigger:

namespace EqidManager
{
 using IOCContainer = IServiceProvider;
 // Quartz.Net啟動(dòng)后注冊(cè)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()
    // 每隔一小時(shí)同步一次
    .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 :實(shí)現(xiàn)在Timer觸發(fā)的時(shí)候注入生成對(duì)應(yīng)的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)
  {
  }
 }
}

③結(jié)合ASpNet Core 注入組件;綁定Quartz.Net

//-------------------------------截取自Startup文件------------------------
......
services.AddTransient<UsageCounterSyncJob>();  // 這里使用瞬時(shí)依賴注入
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 網(wǎng)站低頻訪問(wèn)導(dǎo)致工作進(jìn)程進(jìn)入閑置狀態(tài)的 解決辦法

IIS為網(wǎng)站默認(rèn)設(shè)定了20min閑置超時(shí)時(shí)間:20分鐘內(nèi)沒(méi)有處理請(qǐng)求、也沒(méi)有收到新的請(qǐng)求,工作進(jìn)程就進(jìn)入閑置狀態(tài)。


IIS上低頻web訪問(wèn)會(huì)造成工作進(jìn)程關(guān)閉,此時(shí)應(yīng)用程序池回收,Timer等線程資源會(huì)被銷毀;當(dāng)工作進(jìn)程重新運(yùn)作,Timer可能會(huì)重新生成起效, 但我們的設(shè)定的定時(shí)Job可能沒(méi)有按需正確執(zhí)行。

怎么在AspNet Core中實(shí)現(xiàn)一個(gè)web定時(shí)任務(wù)

故為在IIS網(wǎng)站實(shí)現(xiàn)低頻web訪問(wèn)下的定時(shí)任務(wù):


設(shè)置了Idle TimeOut =0;同時(shí)將【應(yīng)用程序池】->【正在回收】->不勾選【回收條件】

關(guān)于怎么在AspNet Core中實(shí)現(xiàn)一個(gè)web定時(shí)任務(wù)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

網(wǎng)站欄目:怎么在AspNetCore中實(shí)現(xiàn)一個(gè)web定時(shí)任務(wù)-創(chuàng)新互聯(lián)
標(biāo)題URL:http://www.rwnh.cn/article46/epeeg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、自適應(yīng)網(wǎng)站、軟件開(kāi)發(fā)全網(wǎng)營(yíng)銷推廣、ChatGPT手機(jī)網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)
连南| 大渡口区| 湟中县| 监利县| 和静县| 桃园市| 河南省| 东源县| 湘乡市| 新龙县| 巍山| 南华县| 昭平县| 五河县| 沙河市| 尚志市| 泸定县| 乐业县| 蓬溪县| 洪江市| 新沂市| 和静县| 保康县| 西乌| 迁安市| 聊城市| 柯坪县| 黑山县| 肇州县| 郁南县| 张家口市| 额敏县| 南京市| 乌鲁木齐市| 策勒县| 昌黎县| 禹城市| 稷山县| 吴川市| 苍南县| 金平|