使用任务过滤器¶

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

定义过滤器

  1. public class LogEverythingAttribute : JobFilterAttribute,
  2. IClientFilter, IServerFilter, IElectStateFilter, IApplyStateFilter
  3. {
  4. private static readonly ILog Logger = LogProvider.GetCurrentClassLogger();
  5.  
  6. public void OnCreating(CreatingContext context)
  7. {
  8. Logger.InfoFormat("Creating a job based on method `{0}`...", context.Job.Method.Name);
  9. }
  10.  
  11. public void OnCreated(CreatedContext context)
  12. {
  13. Logger.InfoFormat(
  14. "Job that is based on method `{0}` has been created with id `{1}`",
  15. context.Job.Method.Name,
  16. context.BackgroundJob?.Id);
  17. }
  18.  
  19. public void OnPerforming(PerformingContext context)
  20. {
  21. Logger.InfoFormat("Starting to perform job `{0}`", context.BackgroundJob.Id);
  22. }
  23.  
  24. public void OnPerformed(PerformedContext context)
  25. {
  26. Logger.InfoFormat("Job `{0}` has been performed", context.BackgroundJob.Id);
  27. }
  28.  
  29. public void OnStateElection(ElectStateContext context)
  30. {
  31. var failedState = context.CandidateState as FailedState;
  32. if (failedState != null)
  33. {
  34. Logger.WarnFormat(
  35. "Job `{0}` has been failed due to an exception `{1}`",
  36. context.BackgroundJob.Id,
  37. failedState.Exception);
  38. }
  39. }
  40.  
  41. public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
  42. {
  43. Logger.InfoFormat(
  44. "Job `{0}` state was changed from `{1}` to `{2}`",
  45. context.BackgroundJob.Id,
  46. context.OldStateName,
  47. context.NewState.Name);
  48. }
  49.  
  50. public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
  51. {
  52. Logger.InfoFormat(
  53. "Job `{0}` state `{1}` was unapplied.",
  54. context.BackgroundJob.Id,
  55. context.OldStateName);
  56. }
  57. }

使用过滤器

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

  1. [LogEverything]
  2. public class EmailService
  3. {
  4. [LogEverything]
  5. public static void Send() { }
  6. }
  7.  
  8. GlobalJobFilters.Filters.Add(new LogEverythingAttribute());

原文:

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