使用任务过滤器¶

所有任务都实现了 Chain-of-responsibility 模式并且可以像ASP.NET MVC操作过滤器一样被拦截。

定义过滤器

  1. publicclassLogEverythingAttribute:JobFilterAttribute,
    IClientFilter,IServerFilter,IElectStateFilter,IApplyStateFilter
    {
    privatestaticreadonlyILogLogger=LogProvider.GetCurrentClassLogger();

    publicvoidOnCreating(CreatingContextcontext)
    {
    Logger.InfoFormat("Creating a job based on method {0}…",context.Job.Method.Name);
    }

    publicvoidOnCreated(CreatedContextcontext)
    {
    Logger.InfoFormat(
    "Job that is based on method {0} has been created with id {1}",
    context.Job.Method.Name,
    context.BackgroundJob?.Id);
    }

    publicvoidOnPerforming(PerformingContextcontext)
    {
    Logger.InfoFormat("Starting to perform job {0}",context.BackgroundJob.Id);
    }

    publicvoidOnPerformed(PerformedContextcontext)
    {
    Logger.InfoFormat("Job {0} has been performed",context.BackgroundJob.Id);
    }

    publicvoidOnStateElection(ElectStateContextcontext)
    {
    varfailedState=context.CandidateStateasFailedState;
    if(failedState!=null)
    {
    Logger.WarnFormat(
    "Job {0} has been failed due to an exception {1}",
    context.BackgroundJob.Id,
    failedState.Exception);
    }
    }

    publicvoidOnStateApplied(ApplyStateContextcontext,IWriteOnlyTransactiontransaction)
    {
    Logger.InfoFormat(
    "Job {0} state was changed from {1} to {2}",
    context.BackgroundJob.Id,
    context.OldStateName,
    context.NewState.Name);
    }

    publicvoidOnStateUnapplied(ApplyStateContextcontext,IWriteOnlyTransactiontransaction)
    {
    Logger.InfoFormat(
    "Job {0} state {1} was unapplied.",
    context.BackgroundJob.Id,
    context.OldStateName);
    }
    }


使用过滤器


像ASP.NET过滤器一样,您可以在方法,类和全局上应用过滤器:


  1. [LogEverything]
    publicclassEmailService
    {
    [LogEverything]
    publicstaticvoidSend(){}
    }

    GlobalJobFilters.Filters.Add(newLogEverythingAttribute());

原文:

http://hangfirezh.zhs.press/extensibility/using-job-filters.html[TOC]