Hangfire .NET Core - 获取排队的作业列表

Hangfire .NET Core - Get enqueued jobs list

Hangfire API 中是否有获取排队作业的方法(可能通过作业 ID 或其他方式)?

我对此做了一些研究,但我找不到任何东西。

请帮帮我。

我在Hangfire官方论坛找到了答案

这是 link: https://discuss.hangfire.io/t/checking-for-a-job-state/57/4

根据 Hangfire 的官方开发人员的说法,JobStorage.Current.GetMonitoringApi() 还为您提供了有关作业、队列和配置服务器的所有详细信息!

Hangfire 仪表板似乎正在使用相同的 API。

:-)

我 运行 遇到一个案例,我想查看特定队列的 ProcessingJobs、EnqueuedJobs 和 AwaitingState 作业。我从来没有找到开箱即用的好方法,但我确实发现了一种在 Hangfire 中创建“一组”作业的方法。我的解决方案是将每个作业添加到一个集合中,然后查询匹配集中的所有项目。当作业达到最终状态时,从集合中删除作业。

这是创建集合的属性:

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) { }
}

你这样装饰你的工作:

[ProcessQueue("queueName")]
public async Task DoSomething() {}

那么您可以查询如下设置:

using (var conn = JobStorage.Current.GetConnection())
{
    var storage = (JobStorageConnection)conn;
    if (storage != null)
    {
        var itemsInSet = storage.GetAllItemsFromSet("queueName");
    }
}