我已经通过使用Hangfire库计划了一份工作。我的预定代码如下。
BackgroundJob.Schedule(() => UserRepository.DownGradeUserPlan(2),TimeSpan.FromDays(7));
public static bool DownGradeUserPlan(int userId)
{
//Write login here
}
现在,我想稍后在某些事件中删除此计划作业。
答案 0 :(得分:6)
BackgroundJob.Schedule
返回该作业的ID,您可以使用它删除该作业:
var jobId = BackgroundJob.Schedule(() => UserRepository.DownGradeUserPlan(2),TimeSpan.FromDays(7));
BackgroundJob.Delete(jobId);
答案 1 :(得分:0)
您无需保存其ID即可稍后检索作业。相反,您可以使用Hangfire API的 MonitoringApi 类。请注意,您将需要根据需要过滤出作业。
文本是示例代码中的自定义类。
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