- 编写工作类
public class UTaskEventHanlder : BackgroundJob<UpByTermIdInput>, ITransientDependency
{
private readonly IRepository<EvaluationSystem.EntityDesign.ClassManage, Guid> _classManageRepository;
private readonly ICacheManager _cacheManager;
private readonly IBackgroundJobManager _backgroundJobManager;
public UTaskEventHanlder(IRepository<EvaluationSystem.EntityDesign.ClassManage, Guid> classManageRepository,
ICacheManager cacheManager,
IBackgroundJobManager backgroundJobManager)
{
_backgroundJobManager = backgroundJobManager;
_cacheManager = cacheManager;
_classManageRepository = classManageRepository;
}
[UnitOfWork]
public override void Execute(UpByTermIdInput input)
{
try
{
UnitOfWorkManager.Current.SetTenantId(1);
//查找任务删除 保证执行一次
var ts = _cacheManager.GetCache("_AutoUpClass_" + input.TaskId).GetOrDefault("_AutoUpClass_" + input.TaskId);
if (ts != null)
{
var d= (UpByTermIdTaskInfo)ts;
_backgroundJobManager.Delete(d.JobId);
}
//......省略代码
_cacheManager.GetCache("_AutoUpClass_" + input.gId).Set("_AutoUpClass_" + input.gId, new UpByTermIdTaskInfo { Status = 0, Msg = "执行中", TaskId = input.gId, Progress = $"{1}/{3}" });
//......省略代码
_cacheManager.GetCache("_AutoUpClass_" + input.gId).Set("_AutoUpClass_" + input.gId, new UpByTermIdTaskInfo { Status = 1, Msg = "成功", TaskId = input.gId, Progress = $"{3}/{3}" });
CurrentUnitOfWork.SaveChanges();
}
catch (Exception e)
{
_cacheManager.GetCache("_AutoUpClass_" + input.gId).Set("_AutoUpClass_" + input.gId, new UpByTermIdTaskInfo { Status = 2, Msg = "失败", TaskId = input.gId});
}
}
}
-
调用
public async Task<UpByTermIdTaskInfo> AutoUpClassTestAsync(UpByTermIdInput input) { if (!string.IsNullOrEmpty(input.TaskId)) { //查询状态 var ts = _cacheManager.GetCache("_AutoUpClass_" + input.TaskId).GetOrDefault("_AutoUpClass_" + input.TaskId); if (ts != null) return (UpByTermIdTaskInfo)ts; else return new UpByTermIdTaskInfo { Status = 2, TaskId = input.TaskId, Msg = "失败" }; } else { //首次 string g = Guid.NewGuid().ToString(); var a=await _backgroundJobManager.EnqueueAsync<UTaskEventHanlder, UpByTermIdInput>( new UpByTermIdInput { oldTermId=input.oldTermId,newTermId=input.newTermId,schoolId=input.schoolId,TaskId= g, gId=g}); //设置查询 var taskInfo = new UpByTermIdTaskInfo { Status = 0, Msg = "执行中", TaskId = g,JobId=a }; _cacheManager.GetCache("_AutoUpClass_" + g).Set("_AutoUpClass_" + g, taskInfo, TimeSpan.FromMinutes(10)); return taskInfo; } }
注:执行不完一直执行 容易多次执行 慎重使用
引用https://aspnetboilerplate.com/Pages/Documents/Background-Jobs-And-Workers#background-jobs
及https://www.cnblogs.com/wangyinlon/p/15160497.html