2 回答
TA贡献1859条经验 获得超6个赞
BackgroundJob.Schedule 返回您该作业的 ID,您可以使用它来删除该作业:
var jobId = BackgroundJob.Schedule(() => MyRepository.SomeMethod(2),TimeSpan.FromDays(7));
BackgroundJob.Delete(jobId);
TA贡献1848条经验 获得超10个赞
您无需保存他们的 ID 即可在以后检索作业。相反,您可以使用Hangfire API的MonitoringApi类。请注意,您需要根据需要过滤掉作业。
Text是我的示例代码中的自定义类。
public void ProcessInBackground(Text text)
{
// Some code
}
public void SomeMethod(Text text)
{
// Some code
// Delete existing jobs before adding a new one
DeleteExistingJobs(text.TextId);
BackgroundJob.Enqueue(() => ProcessInBackground(text));
}
private void DeleteExistingJobs(int textId)
{
var monitor = JobStorage.Current.GetMonitoringApi();
var jobsProcessing = monitor.ProcessingJobs(0, int.MaxValue)
.Where(x => x.Value.Job.Method.Name == "ProcessInBackground");
foreach (var j in jobsProcessing)
{
var t = (Text)j.Value.Job.Args[0];
if (t.TextId == textId)
{
BackgroundJob.Delete(j.Key);
}
}
var jobsScheduled = monitor.ScheduledJobs(0, int.MaxValue)
.Where(x => x.Value.Job.Method.Name == "ProcessInBackground");
foreach (var j in jobsScheduled)
{
var t = (Text)j.Value.Job.Args[0];
if (t.TextId == textId)
{
BackgroundJob.Delete(j.Key);
}
}
}
我的参考:https : //discuss.hangfire.io/t/cancel-a-running-job/603/10
- 2 回答
- 0 关注
- 201 浏览
添加回答
举报