简体   繁体   中英

Hangfire .NET Core - Get enqueued jobs list

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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM