设置最大重试次数

dev
嵇文龙 4 days ago
parent ba65c8e7c0
commit 60ae4b2555

@ -25,7 +25,7 @@ namespace DS.WMS.Core
/// <summary>
/// 获取业务库访问对象
/// </summary>
protected ISaasDbService SaasService { get; private set; }
readonly ISaasDbService saasService;
readonly Lazy<ICommonService> commonService;
@ -37,17 +37,22 @@ namespace DS.WMS.Core
{
get
{
_tenantDb ??= SaasService.GetBizDbScopeById(User.TenantId);
_tenantDb ??= saasService.GetBizDbScopeById(User.TenantId);
return _tenantDb;
}
}
IUser _user;
readonly IUser _user;
/// <summary>
/// 获取用户相关信息
/// </summary>
public virtual IUser User => _user;
/// <summary>
/// 当前用户ID
/// </summary>
public readonly long UserId;
/// <summary>
/// 日志记录对象
/// </summary>
@ -61,8 +66,11 @@ namespace DS.WMS.Core
{
ServiceProvider = serviceProvider;
_user = serviceProvider.GetRequiredService<IUser>();
if (_user != null)
UserId = long.Parse(User.UserId);
Db = serviceProvider.GetRequiredService<ISqlSugarClient>();
SaasService = serviceProvider.GetRequiredService<ISaasDbService>();
saasService = serviceProvider.GetRequiredService<ISaasDbService>();
commonService = new Lazy<ICommonService>(serviceProvider.GetRequiredService<ICommonService>());
Logger = new Lazy<ILogger<ServiceBase>>(serviceProvider.GetRequiredService<ILogger<ServiceBase>>());
}

@ -58,6 +58,24 @@ namespace DS.WMS.Core.TaskInteraction.Entity
[SugarColumn(ColumnDescription = "创建时间", IsNullable = false)]
public DateTime CreateTime { get; set; }
/// <summary>
/// 更新人
/// </summary>
[SugarColumn(ColumnDescription = "更新人", IsNullable = true)]
public long? UpdateBy { get; set; }
/// <summary>
/// 更新时间
/// </summary>
[SugarColumn(ColumnDescription = "更新时间", IsNullable = true)]
public DateTime? UpdateTime { get; set; }
/// <summary>
/// 重试次数
/// </summary>
[SugarColumn(ColumnDescription = "重试次数", IsNullable = false)]
public int RetryTimes { get; set; }
/// <summary>
/// 业务ID
/// </summary>

@ -19,11 +19,6 @@ namespace DS.WMS.Core.TaskInteraction.Method
/// </summary>
public class FeeBillTaskService : TaskService, IFeeBillTaskService
{
/// <summary>
/// 当前用户ID
/// </summary>
public readonly long UserId;
readonly ILogger<FeeBillTaskService> logger;
/// <summary>
/// 初始化
@ -32,7 +27,6 @@ namespace DS.WMS.Core.TaskInteraction.Method
public FeeBillTaskService(IServiceProvider provider) : base(provider)
{
logger = provider.GetRequiredService<ILogger<FeeBillTaskService>>();
UserId = long.Parse(User.UserId);
}
/// <summary>
@ -41,19 +35,20 @@ namespace DS.WMS.Core.TaskInteraction.Method
/// <param name="request"></param>
/// <param name="useTransaction"></param>
/// <returns></returns>
public override Task<DataResult> CreateTaskAsync(TaskCreationRequest request, bool useTransaction = true)
public override async Task<DataResult> CreateTaskAsync(TaskCreationRequest request, bool useTransaction = true)
{
if (request.TaskType == TaskBaseTypeEnum.BILL_SENDING)
{
var interval = await GetConfigValueAsync(DEFAULT_JOB_INTERVAL, 60);
request.Jobs ??= [];
request.Jobs.Add(new TaskJob
{
TypeName = typeof(BillSendingTaskJob).FullName!,
NextTriggerTime = DateTime.Now.AddMinutes(60)
NextTriggerTime = DateTime.Now.AddMinutes(interval)
});
}
return base.CreateTaskAsync(request, useTransaction);
return await base.CreateTaskAsync(request, useTransaction);
}
/// <summary>

@ -37,7 +37,8 @@ namespace DS.WMS.Core.TaskInteraction.Method
public class TaskService : ServiceBase, ITaskService, IAuditTaskService
{
internal const long PERMISSION_ID = 1815294400855674880;
internal const string BillSendingInterval = "BillSendingInterval";
internal const string DEFAULT_JOB_INTERVAL = "DefaultJobInterval";
internal const string JOB_MAX_RETRY = "JOB_MAX_RETRY";
/// <summary>
/// 获取支持审核的任务类型
@ -688,10 +689,7 @@ namespace DS.WMS.Core.TaskInteraction.Method
break;
}
var value = await Db.Queryable<SysConfig>().Where(x => x.Code == BillSendingInterval).Select(x => x.Value).FirstAsync();
if (!int.TryParse(value, out int interval))
interval = 60;
var interval = await GetConfigValueAsync(DEFAULT_JOB_INTERVAL, 60);
var list = await TenantDb.Queryable<TaskJob>().Where(x => x.TaskId == task.Id && x.Status != TaskJobStatus.Completed)
.Select(x => new TaskJob
{
@ -703,7 +701,7 @@ namespace DS.WMS.Core.TaskInteraction.Method
if (jobStatus == TaskJobStatus.Ready) //重新设置下次触发时间
foreach (var item in list)
{
item.NextTriggerTime = item.NextTriggerTime.HasValue ?
item.NextTriggerTime = item.NextTriggerTime.HasValue ?
item.NextTriggerTime.Value.AddMinutes(interval) : DateTime.Now.AddMinutes(interval);
}
@ -1398,7 +1396,7 @@ namespace DS.WMS.Core.TaskInteraction.Method
/// <param name="remark">备注</param>
/// <param name="taskTypes">任务类型,不指定任务类型则删除全部任务</param>
/// <returns></returns>
public async Task<DataResult> DeleteAsync(long id, BusinessType? businessType, string? remark = null, params TaskBaseTypeEnum[] taskTypes)
public virtual async Task<DataResult> DeleteAsync(long id, BusinessType? businessType, string? remark = null, params TaskBaseTypeEnum[] taskTypes)
{
if (!await HasAuthorizedAsync())
return DataResult.SuccessedWithDesc(nameof(MultiLanguageConst.ModuleUnauthorized));
@ -1471,15 +1469,40 @@ namespace DS.WMS.Core.TaskInteraction.Method
await ManagerService.SetTaskBaseInfoPropertyWithBsno(id, taskType, null, null, x => x.TASK_DESP == description);
}
/// <summary>
/// 获取系统配置值
/// </summary>
/// <typeparam name="T">值类型</typeparam>
/// <param name="key">配值名称</param>
/// <param name="defaultValue">未获取到配值时的默认值</param>
/// <returns></returns>
protected internal async Task<T?> GetConfigValueAsync<T>(string key, T? defaultValue = default)
{
var value = await Db.Queryable<SysConfig>().Where(x => x.Code == key).Select(x => x.Value).FirstAsync();
if (string.IsNullOrEmpty(value))
return defaultValue;
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch
{
return defaultValue;
}
}
/// <summary>
/// 运行定时任务
/// </summary>
/// <returns></returns>
public async Task RunJobAsync()
public async Task RunJobAsync()
{
var maxRetry = await GetConfigValueAsync(JOB_MAX_RETRY, 10);
var jobs = await TenantDb.Queryable<TaskJob>()
.InnerJoin<BusinessTask>((x, y) => x.TaskId == y.Id)
.Where((x, y) => y.TaskStatus == TaskStatusEnum.Create && x.Status == TaskJobStatus.Ready && x.NextTriggerTime <= SqlFunc.GetDate())
.Where((x, y) => y.TaskStatus == TaskStatusEnum.Create && x.Status == TaskJobStatus.Ready &&
x.NextTriggerTime <= SqlFunc.GetDate() && x.RetryTimes <= maxRetry)
.Select((x, y) => new TaskJob
{
Id = x.Id,
@ -1492,6 +1515,8 @@ namespace DS.WMS.Core.TaskInteraction.Method
if (jobs.Count == 0)
return;
long userId = long.Parse(User.UserId);
var dtNow = DateTime.Now;
var jobContext = new TaskJobContext();
await TenantDb.Ado.BeginTranAsync();
try
@ -1514,6 +1539,7 @@ namespace DS.WMS.Core.TaskInteraction.Method
catch (Exception ex)
{
item.LastException = $"执行作业({item.Id})时发生错误:" + ex.Message + Environment.NewLine + ex.StackTrace;
item.RetryTimes++;
jobContext.Result = DataResult.Failed(item.LastException);
continue;
}
@ -1523,6 +1549,9 @@ namespace DS.WMS.Core.TaskInteraction.Method
item.Status = TaskJobStatus.Completed;
item.NextTriggerTime = null;
}
item.UpdateBy = userId;
item.UpdateTime = dtNow;
}
}
@ -1530,7 +1559,10 @@ namespace DS.WMS.Core.TaskInteraction.Method
{
x.Status,
x.NextTriggerTime,
x.LastException
x.LastException,
x.RetryTimes,
x.UpdateBy,
x.UpdateTime
}).ExecuteCommandAsync();
var finishedJobs = jobs.FindAll(x => x.Status == TaskJobStatus.Completed);
@ -1545,8 +1577,8 @@ namespace DS.WMS.Core.TaskInteraction.Method
x.TaskId,
x.Status
}).ToListAsync();
var groups = list.GroupBy(x => x.TaskId);
DateTime dtNow = DateTime.Now;
foreach (var group in groups)
{
if (group.Count() == group.Count(x => x.Status == TaskJobStatus.Completed))

Loading…
Cancel
Save