取消或删除预定作业 - HangFire
Cancel or Delete Scheduled Job - HangFire
我已经通过使用 Hangfire 库安排了一个工作。我预定的代码如下。
BackgroundJob.Schedule(() => MyRepository.SomeMethod(2),TimeSpan.FromDays(7));
public static bool DownGradeUserPlan(int userId)
{
//Write logic here
}
现在我想稍后在某些事件中删除此计划作业。
BackgroundJob.Schedule
returns 你是那个职位的id,你可以用它来删除这个职位:
var jobId = BackgroundJob.Schedule(() => MyRepository.SomeMethod(2),TimeSpan.FromDays(7));
BackgroundJob.Delete(jobId);
您无需保存他们的 ID 即可在以后检索工作。相反,您可以利用 Hangfire API 的 MonitoringApi class。请注意,您需要根据需要筛选职位。
Text 是我在示例代码中自定义的 class。
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
我已经通过使用 Hangfire 库安排了一个工作。我预定的代码如下。
BackgroundJob.Schedule(() => MyRepository.SomeMethod(2),TimeSpan.FromDays(7));
public static bool DownGradeUserPlan(int userId)
{
//Write logic here
}
现在我想稍后在某些事件中删除此计划作业。
BackgroundJob.Schedule
returns 你是那个职位的id,你可以用它来删除这个职位:
var jobId = BackgroundJob.Schedule(() => MyRepository.SomeMethod(2),TimeSpan.FromDays(7));
BackgroundJob.Delete(jobId);
您无需保存他们的 ID 即可在以后检索工作。相反,您可以利用 Hangfire API 的 MonitoringApi class。请注意,您需要根据需要筛选职位。
Text 是我在示例代码中自定义的 class。
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