Reputation: 69
My requirement is to process only latest jobs and ignore older jobs. How do I configure that in Hangfire?
I have tried IApplyStateFilter for setting ExpirationAttribute
public class ExpirationAttribute : JobFilterAttribute, IApplyStateFilter
{
private int _hours;
public ExpirationAttribute(int hours)
{
_hours = hours;
}
public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
{
context.JobExpirationTimeout = TimeSpan.FromHours(_hours);
}
public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
{
context.JobExpirationTimeout = TimeSpan.FromHours(_hours);
}
}
Upvotes: 1
Views: 393
Reputation: 802
Another option (or maybe as a failsafe mechanism) is to check the creation DateTime of the job when it is started. The downside is that the Job will be queued and marked as completed.
public static void MyJob(PerformContext context)
{
if (DateTime.Now.Subtract(context.BackgroundJob.CreatedAt).TotalHours >= 1)
{
// Job is older than 1 hour
return;
}
// Process job...
}
Upvotes: 0
Reputation: 530
You could do something similar to this:
public class ExpirationAttribute : JobFilterAttribute, IElectStateFilter
{
private int _hours;
public ExpirationAttribute(int hours)
{
_hours = hours;
}
public void OnStateElection(ElectStateContext context)
{
var processing = context.CandidateState as ProcessingState;
if (processing == null)
{
return;
}
if (DateTime.UtcNow - context.BackgroundJob.CreatedAt > TimeSpan.FromHours(_hours))
{
context.CandidateState = new SucceededState(new { }, 0, 0) { Reason = "Execution skipped due to expiration." };
}
}
}
It simply moves jobs past their expiration to succeeded instead of processing them. I haven't tested it at all but should be generally correct.
Upvotes: 1