我有一个存储每个线程数据的api,并使用HttpContext.Current
检索。
我试图重构这个类来从hangfire作业调用 - 我想知道是否有一个等效的静态方法来检索hangfire执行上下文。
如果没有,我还想知道hangfire作业和线程之间是否存在1:1的关系。我找不到任何关于hangfire工作生命周期的文档 - 即threadstart -> job start -> job end -> thread dispose
,或者1个线程是否可以同时处理多个作业,即threadstart -> job1 start, job2 start, job3 start, job1 end, job4 start,job2 end, job1 end, job3 end -> thread dispose
答案 0 :(得分:3)
从 - https://discuss.hangfire.io/t/how-to-get-jobid-within-job/851/4
[ThreadStatic]
变量将在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());
答案 1 :(得分:2)
在此寻找其他东西时,执行此操作的较新方法(适用于1.6.20,不确定它能回溯多远)是在表达式调用和hangfire的方法中使用Server.PerformContext类型的参数。会自动进行设置(例如网站关闭的取消令牌)
如果您原谅了VB代码,则我对工作方法有此要求
<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)
我通过以下方式创建工作
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)
然后在RunJob方法中获取我使用的ID
hfContext.BackgroundJob.Id