Hangfire: How to get state of a job?

Created on 8 Jul 2015  路  5Comments  路  Source: HangfireIO/Hangfire

Here's a question: is there an api available to query Hangfire for a given job's current state?

Something like:

var jobState = BackgroundJob.GetState("<id>");

... where jobState is possibly an enum of sorts that could be either one of:

image

Thank you.

Most helpful comment

The JobData class contains a State property:
https://github.com/HangfireIO/Hangfire/blob/master/src/Hangfire.Core/Storage/JobData.cs#L24

You can retrieve the JobData for a job using:

IStorageConnection connection = JobStorage.Current.GetConnection();
JobData jobData = connection.GetJobData(jobId);
string stateName = jobData.State;

There's also a StateData class and related connection.GetStateData(JobId) method:
https://github.com/HangfireIO/Hangfire/blob/5a770aab402b820f262f0872b18c2d3304bb7128/src/Hangfire.Core/Storage/StateData.cs

There is no state enumeration as the states are actually represented by a set of classes, each of which have static string describing the name:
https://github.com/HangfireIO/Hangfire/blob/5a770aab402b820f262f0872b18c2d3304bb7128/src/Hangfire.Core/States/EnqueuedState.cs#L28

All 5 comments

The JobData class contains a State property:
https://github.com/HangfireIO/Hangfire/blob/master/src/Hangfire.Core/Storage/JobData.cs#L24

You can retrieve the JobData for a job using:

IStorageConnection connection = JobStorage.Current.GetConnection();
JobData jobData = connection.GetJobData(jobId);
string stateName = jobData.State;

There's also a StateData class and related connection.GetStateData(JobId) method:
https://github.com/HangfireIO/Hangfire/blob/5a770aab402b820f262f0872b18c2d3304bb7128/src/Hangfire.Core/Storage/StateData.cs

There is no state enumeration as the states are actually represented by a set of classes, each of which have static string describing the name:
https://github.com/HangfireIO/Hangfire/blob/5a770aab402b820f262f0872b18c2d3304bb7128/src/Hangfire.Core/States/EnqueuedState.cs#L28

Thank you!

Ummm, @yngndrw anyway to access the schedule info. for a scheduled job?

What you're interested in is the EnqueueAt property on the ScheduledState:
https://github.com/HangfireIO/Hangfire/blob/5a770aab402b820f262f0872b18c2d3304bb7128/src/Hangfire.Core/States/ScheduledState.cs#L41

Depending on where you get it from you may need to deserialise the DateTime, but there is a helper for that:
https://github.com/HangfireIO/Hangfire/blob/5a770aab402b820f262f0872b18c2d3304bb7128/src/Hangfire.SqlServer/SqlServerMonitoringApi.cs#L107

I believe you should be able to get this from the StateData.Data dictionary property returned by the IStorageConnection.GetStateData(jobId) method mentioned above.

Thank you!!

Was this page helpful?
0 / 5 - 0 ratings