【发布时间】:2019-01-17 15:35:17
【问题描述】:
Hangfire API 中是否有获取排队作业的方法(可能通过作业 ID 或其他方式)?
我对此进行了一些研究,但我找不到任何东西。
请帮帮我。
【问题讨论】:
标签: c# background-process asp.net-core-webapi hangfire
Hangfire API 中是否有获取排队作业的方法(可能通过作业 ID 或其他方式)?
我对此进行了一些研究,但我找不到任何东西。
请帮帮我。
【问题讨论】:
标签: c# background-process asp.net-core-webapi hangfire
我在Hangfire官方论坛找到了答案。
这里是链接: https://discuss.hangfire.io/t/checking-for-a-job-state/57/4
据 Hangfire 官方开发者称,JobStorage.Current.GetMonitoringApi() 还为您提供有关作业、队列和已配置服务器的所有详细信息!
Hangfire Dashboard 似乎正在使用相同的 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");
}
}
【讨论】: