Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a static hangfire context getter, similar to HttpContext.Current

Tags:

hangfire

I have an existing api that stores data per-thread and is retrieved using HttpContext.Current.

I'm trying to refactor this class to be called from a hangfire job -- I want to know if there is an equivalent static method for retrieving the hangfire execution context.

If not, I would also like to know if there is a 1:1 relationship between hangfire jobs and threads. I couldn't find any documentation about the lifetime of a hangfire job -- ie threadstart -> job start -> job end -> thread dispose, or if 1 thread could process multiple jobs simultaneously, ie threadstart -> job1 start, job2 start, job3 start, job1 end, job4 start,job2 end, job1 end, job3 end -> thread dispose

like image 366
scaryman Avatar asked Jan 29 '16 22:01

scaryman


2 Answers

From - https://discuss.hangfire.io/t/how-to-get-jobid-within-job/851/4

a [ThreadStatic] variable will do the trick in a ServerFilter

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.BackgroundJobId;
    }
}

// And register it
GlobalConfiguration.Configuration.UseFilter(new JobContext());
like image 131
scaryman Avatar answered Oct 14 '22 23:10

scaryman


Came across this looking for something else, the newer way (works with 1.6.20, not sure how far back it works) of doing it is to have a parameter of type Server.PerformContext in the method your expression calls and hangfire will set it automatically (like the cancellation token for site shutdowns)

if you forgive the VB code i have this sigature for the job method

        <DisplayName("{0}")> 'use jobname param as the name of the job
        Sub RunJob(jobName As String, configID as Integer  hfContext As Server.PerformContext, cancellationToken As Hangfire.IJobCancellationToken)

I create the job with

        Dim jobExpression As Linq.Expressions.Expression(Of Action(Of HangfireJob)) = Sub(x) x.RunJob(opt.JobName, opt.configID, Nothing, JobCancellationToken.Null)
        RecurringJob.AddOrUpdate(Of HangfireJob)(opt.SchedulerSystemJobID, jobExpression, opt.RecurringCronSchedule, tzinfo)

And in the RunJob method to get the ID i use

hfContext.BackgroundJob.Id
like image 27
Tim Hall Avatar answered Oct 14 '22 22:10

Tim Hall