How to get jobid within job?

Hi
How to get jobid within job? I need the jobid so that i can update process status (i.e percentage) to SQL table. My table is using jobid as primary key as it is unique.

Please advice. thank you

1 Like

How about simply passing job ID as one of parameters? Nobody knows this better than calling code, so, why not.

Hi
Shall you show sample code?

MyTask task = new MyTask();
var jobId = BackgroundJob.Enqueue( ( ) => MyTask.Execute( ... )  );

Since jobId is returned after job enqueued, how could I pass it as parameter to my task? As I understand, Hangfire will activate my class again for execution instead of using the instance that I created.

Of course, I was thinking to self-generate my own id, pass to myTask. Then, use my id map to jobId returned by Hangfire.

But, before I use this approach, I am thinking if that is more direct way.

Please advice. thank you

KKChan! Hi!
In my opinion, you’re right when think to self generate your own id, and after pass to task, this way brings the job for your control, and with this ID you can do everything :smile:

General recommendation is to forget about Hangfire in your jobs (except IJobCancellationToken :frowning:). However, you can create a server filter for that:

public class JobContext : IServerFilter
{
    [ThreadStatic]
    private static string _jobId;

    public static string JobId { get { return _jobId; } set { _jobId = value; } }

    public void OnPerforming(PerformingContext context)
    {
        JobId = context.JobId;
    }
}

// And register it
GlobalConfiguration.Configuration.UseFilter(new JobContext());
1 Like

nice, this JobContext works well. have been searching for such solution for some time because the attribute solution never worked.

I realise this is an old discussion, however the JobContext storing the JobId in a ThreadStatic field will no longer work with the 1.6.0-beta1 version of Hangfire if you invoke a Job using the async keyword returning a Task. The continuation causes the context to appear on a different thread than what the JobFilter is executing.

It looks like this pull request would be required: https://github.com/HangfireIO/Hangfire/pull/466

The updated and correct way to get jobid inside a Job is now explained here Use Hangfire job id in the code

1 Like