我有一个现有的api,它按线程存储数据,并使用检索HttpContext.Current。
我正在尝试重构该类以从hangfire作业中调用-我想知道是否存在用于检索hangfire执行上下文的等效静态方法。
如果不是,我还想知道hangfire作业和线程之间是否存在1:1的关系。我找不到有关hangfire作业生命周期的任何文档-即threadstart -> job start -> job end -> thread dispose,或者是否有一个线程可以同时处理多个作业,即threadstart -> job1 start, job2 start, job3 start, job1 end, job4 start,job2 end, job1 end, job3 end -> thread dispose
来自 - 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());
Run Code Online (Sandbox Code Playgroud)
遇到这个寻找其他东西,更新的方法(适用于 1.6.20,不确定它能工作多久)是在表达式调用的方法中拥有一个类型为 Server.PerformContext 的参数,hangfire 将设置它自动(如站点关闭的取消令牌)
如果你原谅 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)
Run Code Online (Sandbox Code Playgroud)
我创造了这份工作
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)
Run Code Online (Sandbox Code Playgroud)
并在 RunJob 方法中获取我使用的 ID
hfContext.BackgroundJob.Id
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2969 次 |
| 最近记录: |