diff --git a/HybirdFrameworkCore/AutoTask/ITask.cs b/HybirdFrameworkCore/AutoTask/ITask.cs new file mode 100644 index 0000000..74b6fc3 --- /dev/null +++ b/HybirdFrameworkCore/AutoTask/ITask.cs @@ -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(); +} diff --git a/HybirdFrameworkCore/AutoTask/TaskInfo.cs b/HybirdFrameworkCore/AutoTask/TaskInfo.cs new file mode 100644 index 0000000..859e81f --- /dev/null +++ b/HybirdFrameworkCore/AutoTask/TaskInfo.cs @@ -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; } +} diff --git a/HybirdFrameworkCore/AutoTask/TaskInit.cs b/HybirdFrameworkCore/AutoTask/TaskInit.cs new file mode 100644 index 0000000..d896567 --- /dev/null +++ b/HybirdFrameworkCore/AutoTask/TaskInit.cs @@ -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 TaskMap = new(); + + public static void Init() + { + var list = new List(); + 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(); + } + } +} diff --git a/Service/Cloud/Client/MyTask/ChargeOrderUploadTask.cs b/Service/Cloud/Client/MyTask/ChargeOrderUploadTask.cs index 70bbf56..b62b72e 100644 --- a/Service/Cloud/Client/MyTask/ChargeOrderUploadTask.cs +++ b/Service/Cloud/Client/MyTask/ChargeOrderUploadTask.cs @@ -1,42 +1,66 @@ using Entity.DbModel.Station; using HybirdFrameworkCore.Autofac.Attribute; +using HybirdFrameworkCore.AutoTask; using log4net; using Repository.Station; -using Service.BusinessTask; namespace Service.Cloud.Client.MyTask; -[Scope("SingleInstance")] -public class ChargeOrderUploadTask : AbstractTaskHandler +[Scope] +public class ChargeOrderUploadTask : ITask { private static readonly ILog Log = LogManager.GetLogger(typeof(ChargeOrderUploadTask)); + private volatile bool _stop; + public ChargeOrderRepository _chargeOrderRepository { get; set; } - protected override int Interval() + public int Interval() { return 1000 * 10; } - protected override void Handle() + public void Handle() { - List? chargeOrders = _chargeOrderRepository.QueryListByClause(it => it.CloudReportStatus ==0 && it.CanUpload == 1); - - Log.Info($"there are {chargeOrders?.Count ?? 0} to upload"); - if (chargeOrders is { Count: > 0 }) + try { - - var group = chargeOrders.GroupBy(it => it.CloudChargeOrder); - foreach (IGrouping grouping in group) + List? chargeOrders = + _chargeOrderRepository.QueryListByClause(it => it.CloudReportStatus == 0 && it.CanUpload == 1); + + Log.Info($"there are {chargeOrders?.Count ?? 0} to upload"); + if (chargeOrders is { Count: > 0 }) { - List orders = grouping.ToList(); - CloudClientMgr.CloudClient?.PublishChargeOrder(orders, 1); + var group = chargeOrders.GroupBy(it => it.CloudChargeOrder); + foreach (IGrouping grouping in group) + { + List orders = grouping.ToList(); + CloudClientMgr.CloudClient?.PublishChargeOrder(orders, 1); + } } } + catch (Exception e) + { + Log.Error(e); + } } - protected override string Name() + public string Name() { return "ChargeOrderUploadTask"; } -} \ No newline at end of file + + public bool Stoped() + { + return _stop; + } + + public void Stop() + { + _stop = true; + } + + public void ResetStop() + { + _stop = false; + } +} diff --git a/Service/Execute/StationSoftMgr.cs b/Service/Execute/StationSoftMgr.cs index f3464e5..fe21d77 100644 --- a/Service/Execute/StationSoftMgr.cs +++ b/Service/Execute/StationSoftMgr.cs @@ -1,8 +1,5 @@ -using Autofac; -using HybirdFrameworkCore.Autofac; -using Service.BusinessTask; +using Service.BusinessTask; using Service.BusinessTask.MyTask; -using Service.Cloud.Client.MyTask; namespace Service.Execute { @@ -16,7 +13,6 @@ namespace Service.Execute private static readonly AbstractTaskHandler SwapOrderReportCloudTask = new SwapOrderReportCloudTask(); private static readonly AbstractTaskHandler BatteryMoveTask = new BatteryMoveTask(); - private static readonly AbstractTaskHandler ChargeOrderUploadTask = AppInfo.Container.Resolve(); #region Task @@ -28,7 +24,6 @@ namespace Service.Execute { SwapOrderReportCloudTask.Start(); BatteryMoveTask.Start(); - ChargeOrderUploadTask.Start(); } /// @@ -62,4 +57,4 @@ namespace Service.Execute #endregion 换电流程启动 } -} \ No newline at end of file +} diff --git a/WebStarter/Controllers/System/TaskController.cs b/WebStarter/Controllers/System/TaskController.cs new file mode 100644 index 0000000..fd7b5d6 --- /dev/null +++ b/WebStarter/Controllers/System/TaskController.cs @@ -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 +{ + /// + /// 获取任务列表 + /// + /// + [HttpGet("/GetAll")] + public Result> GetAll() + { + List result = new(); + foreach (var (key, value) in TaskInit.TaskMap) + { + result.Add(new TaskInfo() + { + Name = key, + Interval = value.Interval(), + Stoped = value.Stoped() + }); + } + + return Result>.Success(result); + } + + /// + /// 停止任务 + /// + /// + /// + [HttpGet("/stop/{taskName}")] + public Result Stop(string taskName) + { + if (TaskInit.TaskMap.TryGetValue(taskName, out var task)) + { + task.Stop(); + return Result.Success(task.Stoped()); + } + + return Result.Fail("任务不存在"); + } + + + /// + /// 启动任务 + /// + /// + /// + [HttpGet("/start/{taskName}")] + public Result Start(string taskName) + { + if (TaskInit.TaskMap.TryGetValue(taskName, out var task)) + { + task.Start(); + return Result.Success(task.Stoped()); + } + + return Result.Fail("任务不存在"); + } +} diff --git a/WebStarter/Program.cs b/WebStarter/Program.cs index abaf9d5..c3190a1 100644 --- a/WebStarter/Program.cs +++ b/WebStarter/Program.cs @@ -3,6 +3,7 @@ using Autofac; using Autofac.Extensions.DependencyInjection; using Entity.Dto.Resp; using HybirdFrameworkCore.Autofac; +using HybirdFrameworkCore.AutoTask; using HybirdFrameworkCore.Configuration; using HybirdFrameworkCore.Entity; using HybirdFrameworkCore.Redis; @@ -31,9 +32,9 @@ builder.Host.ConfigureContainer(cb => ConnectionString = AppSettingsConstVars.DbSqlConnection, // 设置数据库连接字符串 DbType = AppSettingsConstVars.DbDbType == IocDbType.MySql.ToString() ? DbType.MySql : DbType.SqlServer, IsAutoCloseConnection = true, - + InitKeyType = InitKeyType.Attribute // 如果使用实体类的属性进行主键标识,请设置为 InitKeyType.Attr - + }); return db; }).As().SingleInstance(); @@ -42,7 +43,7 @@ builder.Host.ConfigureContainer(cb => }); -// 注册自定义映射 +// 注册自定义映射 var mapper = new SysMenuMapper(); mapper.Register(TypeAdapterConfig.GlobalSettings); @@ -66,7 +67,7 @@ builder.Services.AddCors(options => //redis 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"); if (redisConnectionString != null && instanceName != null) 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, "Entity.xml"), true); c.IncludeXmlComments(Path.Combine(basePath, "HybirdFrameworkCore.xml"), true); - - + + }); builder.Services.AddControllers().AddJsonOptions(configure => @@ -168,5 +169,7 @@ if (AppSettingsHelper.GetBool("task", "enable")) StationSoftMgr.StartTasks(); } +TaskInit.Init(); + -app.Run(); \ No newline at end of file +app.Run();