Is there a method in the Hangfire API to get an enqueued job (probably by a Job id or something)?
I have done some research on this, but I could not find anything.
Please help me.
Is there a method in the Hangfire API to get an enqueued job (probably by a Job id or something)?
I have done some research on this, but I could not find anything.
Please help me.
I have found the answer in the official forum of Hangfire.
Here is the link: https://discuss.hangfire.io/t/checking-for-a-job-state/57/4
According to an official developer of Hangfire, JobStorage.Current.GetMonitoringApi()
gives you all the details regarding Jobs, Queues and the configured servers too!
It seems that this same API is being used by the Hangfire Dashboard.
:-)
I ran into a case where I wanted to see ProcessingJobs, EnqueuedJobs, and AwaitingState jobs for a particular queue. I never found a great way to do this out of the box, but I did discover a way to create a "set" of jobs in Hangfire. My solution was to add each job to a set, then later query for all items in the matching set. When the job reaches a final state, remove the job from the set.
Here's the attribute to create the set:
public class ProcessQueueAttribute : JobFilterAttribute, IApplyStateFilter
{
private readonly string _queueName;
public ProcessQueueAttribute()
: base() { }
public ProcessQueueAttribute(string queueName)
: this()
{
_queueName = queueName;
}
public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
{
if (string.IsNullOrEmpty(context.OldStateName))
{
transaction.AddToSet(_queueName, context.BackgroundJob.Id);
}
else if (context.NewState.IsFinal)
{
transaction.RemoveFromSet(_queueName, context.BackgroundJob.Id);
}
}
public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction) { }
}
You decorate your job this way:
[ProcessQueue("queueName")]
public async Task DoSomething() {}
Then you can query that set as follows:
using (var conn = JobStorage.Current.GetConnection())
{
var storage = (JobStorageConnection)conn;
if (storage != null)
{
var itemsInSet = storage.GetAllItemsFromSet("queueName");
}
}
© 2022 - 2024 — McMap. All rights reserved.