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 關注
- 259 瀏覽
添加回答
舉報