kreta/Kreta.Job.Tasks.Core/JobStateWatcherAttribute.cs
2024-03-13 00:33:46 +01:00

47 lines
1.7 KiB
C#

using System;
using System.Linq;
using Hangfire.States;
namespace Kreta.Job.Tasks.Core
{
public class JobStateWatcherAttribute : Hangfire.Common.JobFilterAttribute, Hangfire.States.IElectStateFilter
{
public OnAttemptsReached AttemptsReached { get; set; }
public JobStateWatcherAttribute(Type delegateInstance, string delegateName)
{
try
{
AttemptsReached = (OnAttemptsReached)Delegate.CreateDelegate(typeof(OnAttemptsReached), delegateInstance, delegateName);
}
catch (Exception ex)
{
throw new ApplicationException("OnAttemptsReached típusúnak kell lennie a delegáltnak.", ex);
}
}
public void OnStateElection(ElectStateContext context)
{
var state = context.CandidateState as FailedState;
if (state == null)
{
return;
}
var actualRetryCount = context.GetJobParameter<int>("RetryCount");
var automaticRetryAttribute = context.BackgroundJob.Job.Method.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(Hangfire.AutomaticRetryAttribute));
if (automaticRetryAttribute != null)
{
var attempts = automaticRetryAttribute.NamedArguments.FirstOrDefault(x => x.MemberName == "Attempts");
if (attempts.MemberInfo != null)
{
int maxRetryCounts = (int)attempts.TypedValue.Value;
if (maxRetryCounts == actualRetryCount)
{
AttemptsReached?.Invoke(context.BackgroundJob.Id);
}
}
}
}
}
}