任务框架

master
rszn 6 months ago
parent 6728923020
commit ce34b813c1

@ -0,0 +1,36 @@
namespace HybirdFrameworkCore.AutoTask;
public interface ITask
{
public string Name();
public int Interval();
public void Handle();
public void Start()
{
Stop();
Thread.Sleep(Interval());
ResetStop();
Thread thread = new Thread(Process)
{
Name = Name(),
IsBackground = true
};
thread.Start();
}
void Process()
{
while (!Stoped())
{
Thread.Sleep(Interval());
Handle();
}
}
public bool Stoped();
public void Stop();
public void ResetStop();
}

@ -0,0 +1,8 @@
namespace HybirdFrameworkCore.AutoTask;
public class TaskInfo
{
public string Name { get; set; }
public int Interval { get; set; }
public bool Stoped { get; set; }
}

@ -0,0 +1,38 @@
using System.Collections.Concurrent;
using Autofac;
using Autofac.Core;
using HybirdFrameworkCore.Autofac;
namespace HybirdFrameworkCore.AutoTask;
public class TaskInit
{
public static readonly ConcurrentDictionary<string, ITask> TaskMap = new();
public static void Init()
{
var list = new List<Type>();
foreach (var reg in AppInfo.Container.ComponentRegistry.Registrations)
foreach (var service in reg.Services)
if (service is TypedService ts)
{
if (ts.ServiceType.GetInterface(nameof(ITask)) != null)
{
list.Add(ts.ServiceType);
}
}
foreach (Type type in list)
{
var resolve = AppInfo.Container.Resolve(type);
ITask task = (ITask)resolve;
if (TaskMap.TryGetValue(task.Name(), out var exist))
{
throw new ArgumentException($"same task name already added {exist.GetType()}");
}
TaskMap.TryAdd(task.Name(), task);
task.Start();
}
}
}

@ -1,42 +1,66 @@
using Entity.DbModel.Station; using Entity.DbModel.Station;
using HybirdFrameworkCore.Autofac.Attribute; using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkCore.AutoTask;
using log4net; using log4net;
using Repository.Station; using Repository.Station;
using Service.BusinessTask;
namespace Service.Cloud.Client.MyTask; namespace Service.Cloud.Client.MyTask;
[Scope("SingleInstance")] [Scope]
public class ChargeOrderUploadTask : AbstractTaskHandler public class ChargeOrderUploadTask : ITask
{ {
private static readonly ILog Log = LogManager.GetLogger(typeof(ChargeOrderUploadTask)); private static readonly ILog Log = LogManager.GetLogger(typeof(ChargeOrderUploadTask));
private volatile bool _stop;
public ChargeOrderRepository _chargeOrderRepository { get; set; } public ChargeOrderRepository _chargeOrderRepository { get; set; }
protected override int Interval() public int Interval()
{ {
return 1000 * 10; return 1000 * 10;
} }
protected override void Handle() public void Handle()
{ {
List<ChargeOrder>? chargeOrders = _chargeOrderRepository.QueryListByClause(it => it.CloudReportStatus ==0 && it.CanUpload == 1); try
Log.Info($"there are {chargeOrders?.Count ?? 0} to upload");
if (chargeOrders is { Count: > 0 })
{ {
List<ChargeOrder>? chargeOrders =
var group = chargeOrders.GroupBy(it => it.CloudChargeOrder); _chargeOrderRepository.QueryListByClause(it => it.CloudReportStatus == 0 && it.CanUpload == 1);
foreach (IGrouping<string,ChargeOrder> grouping in group)
Log.Info($"there are {chargeOrders?.Count ?? 0} to upload");
if (chargeOrders is { Count: > 0 })
{ {
List<ChargeOrder> orders = grouping.ToList(); var group = chargeOrders.GroupBy(it => it.CloudChargeOrder);
CloudClientMgr.CloudClient?.PublishChargeOrder(orders, 1); foreach (IGrouping<string, ChargeOrder> grouping in group)
{
List<ChargeOrder> orders = grouping.ToList();
CloudClientMgr.CloudClient?.PublishChargeOrder(orders, 1);
}
} }
} }
catch (Exception e)
{
Log.Error(e);
}
} }
protected override string Name() public string Name()
{ {
return "ChargeOrderUploadTask"; return "ChargeOrderUploadTask";
} }
}
public bool Stoped()
{
return _stop;
}
public void Stop()
{
_stop = true;
}
public void ResetStop()
{
_stop = false;
}
}

@ -1,8 +1,5 @@
using Autofac; using Service.BusinessTask;
using HybirdFrameworkCore.Autofac;
using Service.BusinessTask;
using Service.BusinessTask.MyTask; using Service.BusinessTask.MyTask;
using Service.Cloud.Client.MyTask;
namespace Service.Execute namespace Service.Execute
{ {
@ -16,7 +13,6 @@ namespace Service.Execute
private static readonly AbstractTaskHandler SwapOrderReportCloudTask = new SwapOrderReportCloudTask(); private static readonly AbstractTaskHandler SwapOrderReportCloudTask = new SwapOrderReportCloudTask();
private static readonly AbstractTaskHandler BatteryMoveTask = new BatteryMoveTask(); private static readonly AbstractTaskHandler BatteryMoveTask = new BatteryMoveTask();
private static readonly AbstractTaskHandler ChargeOrderUploadTask = AppInfo.Container.Resolve<ChargeOrderUploadTask>();
#region Task #region Task
@ -28,7 +24,6 @@ namespace Service.Execute
{ {
SwapOrderReportCloudTask.Start(); SwapOrderReportCloudTask.Start();
BatteryMoveTask.Start(); BatteryMoveTask.Start();
ChargeOrderUploadTask.Start();
} }
/// <summary> /// <summary>
@ -62,4 +57,4 @@ namespace Service.Execute
#endregion 换电流程启动 #endregion 换电流程启动
} }
} }

@ -0,0 +1,67 @@
using HybirdFrameworkCore.Entity;
using HybirdFrameworkCore.AutoTask;
using Microsoft.AspNetCore.Mvc;
namespace WebStarter.Controllers.System;
[Produces("application/json")]
[ApiController]
[Route("api/[controller]")]
public class TaskController
{
/// <summary>
/// 获取任务列表
/// </summary>
/// <returns></returns>
[HttpGet("/GetAll")]
public Result<List<TaskInfo>> GetAll()
{
List<TaskInfo> result = new();
foreach (var (key, value) in TaskInit.TaskMap)
{
result.Add(new TaskInfo()
{
Name = key,
Interval = value.Interval(),
Stoped = value.Stoped()
});
}
return Result<List<TaskInfo>>.Success(result);
}
/// <summary>
/// 停止任务
/// </summary>
/// <param name="taskName"></param>
/// <returns></returns>
[HttpGet("/stop/{taskName}")]
public Result<bool> Stop(string taskName)
{
if (TaskInit.TaskMap.TryGetValue(taskName, out var task))
{
task.Stop();
return Result<bool>.Success(task.Stoped());
}
return Result<bool>.Fail("任务不存在");
}
/// <summary>
/// 启动任务
/// </summary>
/// <param name="taskName"></param>
/// <returns></returns>
[HttpGet("/start/{taskName}")]
public Result<bool> Start(string taskName)
{
if (TaskInit.TaskMap.TryGetValue(taskName, out var task))
{
task.Start();
return Result<bool>.Success(task.Stoped());
}
return Result<bool>.Fail("任务不存在");
}
}

@ -3,6 +3,7 @@ using Autofac;
using Autofac.Extensions.DependencyInjection; using Autofac.Extensions.DependencyInjection;
using Entity.Dto.Resp; using Entity.Dto.Resp;
using HybirdFrameworkCore.Autofac; using HybirdFrameworkCore.Autofac;
using HybirdFrameworkCore.AutoTask;
using HybirdFrameworkCore.Configuration; using HybirdFrameworkCore.Configuration;
using HybirdFrameworkCore.Entity; using HybirdFrameworkCore.Entity;
using HybirdFrameworkCore.Redis; using HybirdFrameworkCore.Redis;
@ -31,9 +32,9 @@ builder.Host.ConfigureContainer<ContainerBuilder>(cb =>
ConnectionString = AppSettingsConstVars.DbSqlConnection, // 设置数据库连接字符串 ConnectionString = AppSettingsConstVars.DbSqlConnection, // 设置数据库连接字符串
DbType = AppSettingsConstVars.DbDbType == IocDbType.MySql.ToString() ? DbType.MySql : DbType.SqlServer, DbType = AppSettingsConstVars.DbDbType == IocDbType.MySql.ToString() ? DbType.MySql : DbType.SqlServer,
IsAutoCloseConnection = true, IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute // 如果使用实体类的属性进行主键标识,请设置为 InitKeyType.Attr InitKeyType = InitKeyType.Attribute // 如果使用实体类的属性进行主键标识,请设置为 InitKeyType.Attr
}); });
return db; return db;
}).As<ISqlSugarClient>().SingleInstance(); }).As<ISqlSugarClient>().SingleInstance();
@ -42,7 +43,7 @@ builder.Host.ConfigureContainer<ContainerBuilder>(cb =>
}); });
// 注册自定义映射 // 注册自定义映射
var mapper = new SysMenuMapper(); var mapper = new SysMenuMapper();
mapper.Register(TypeAdapterConfig.GlobalSettings); mapper.Register(TypeAdapterConfig.GlobalSettings);
@ -66,7 +67,7 @@ builder.Services.AddCors(options =>
//redis //redis
var redisConnectionString = AppSettingsHelper.GetContent("Redis", "Connection"); var redisConnectionString = AppSettingsHelper.GetContent("Redis", "Connection");
var instanceName = AppSettingsHelper.GetContent("Redis", "InstanceName");//默认数据库 var instanceName = AppSettingsHelper.GetContent("Redis", "InstanceName");//默认数据库
var defaultDb = int.Parse(AppSettingsHelper.GetContent("Redis", "DefaultDB") ?? "0"); var defaultDb = int.Parse(AppSettingsHelper.GetContent("Redis", "DefaultDB") ?? "0");
if (redisConnectionString != null && instanceName != null) if (redisConnectionString != null && instanceName != null)
builder.Services.AddSingleton(new RedisHelper(redisConnectionString, instanceName, defaultDb)); builder.Services.AddSingleton(new RedisHelper(redisConnectionString, instanceName, defaultDb));
@ -88,8 +89,8 @@ builder.Services.AddSwaggerGen(c =>
c.IncludeXmlComments(Path.Combine(basePath, "WebStarter.xml"), true); c.IncludeXmlComments(Path.Combine(basePath, "WebStarter.xml"), true);
c.IncludeXmlComments(Path.Combine(basePath, "Entity.xml"), true); c.IncludeXmlComments(Path.Combine(basePath, "Entity.xml"), true);
c.IncludeXmlComments(Path.Combine(basePath, "HybirdFrameworkCore.xml"), true); c.IncludeXmlComments(Path.Combine(basePath, "HybirdFrameworkCore.xml"), true);
}); });
builder.Services.AddControllers().AddJsonOptions(configure => builder.Services.AddControllers().AddJsonOptions(configure =>
@ -168,5 +169,7 @@ if (AppSettingsHelper.GetBool("task", "enable"))
StationSoftMgr.StartTasks(); StationSoftMgr.StartTasks();
} }
TaskInit.Init();
app.Run(); app.Run();

Loading…
Cancel
Save