瀏覽代碼

1. reduce CPU usage
2. clear unnecessary IServiceProvider dependency

Robert 1 年之前
父節點
當前提交
1e9eb6cdf7

+ 37 - 0
EVCB_OCPP.TaskScheduler/Helper/TimerHelper.cs

@@ -0,0 +1,37 @@
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.TaskScheduler.Helper;
+
+public class TimerHelper : IDisposable
+{
+    public static TimerHelper Start(string name, ILogger logger)
+    {
+        return new TimerHelper(name, logger);
+    }
+
+    private readonly string name;
+    private readonly ILogger logger;
+    private readonly Stopwatch timer;
+
+    private TimerHelper(string name, ILogger logger)
+    {
+        this.name = name;
+        this.logger = logger;
+        this.timer = Stopwatch.StartNew();
+    }
+
+    public void Dispose()
+    {
+        timer.Stop();
+        if(timer.ElapsedMilliseconds > 1000)
+        {
+            logger.LogWarning("{0} cost {1} secs", name, timer.ElapsedMilliseconds / 1000);
+        }
+    }
+}

+ 18 - 25
EVCB_OCPP.TaskScheduler/Jobs/CheckEVSEOnlineJob.cs

@@ -1,4 +1,5 @@
 using Dapper;
+using EVCB_OCPP.TaskScheduler.Helper;
 using EVCB_OCPP.TaskScheduler.Models;
 using Microsoft.Data.SqlClient;
 using Microsoft.Extensions.Configuration;
@@ -6,11 +7,8 @@ using Microsoft.Extensions.Logging;
 using Quartz;
 using System;
 using System.Collections.Generic;
-using System.Configuration;
 using System.Data;
-using System.Diagnostics;
 using System.Linq;
-using System.Text;
 using System.Threading.Tasks;
 
 namespace EVCB_OCPP.TaskScheduler.Jobs
@@ -21,12 +19,12 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
     [DisallowConcurrentExecution]
     public class CheckEVSEOnlineJob : IJob
     {
-        private ILogger logger;
-        private DateTime latestHeartbeatTime = DateTime.Now;
-        private List<EVSEOnlineRecord> updateData = new List<EVSEOnlineRecord>();
-        private List<EVSEOnlineRecord> insertData = new List<EVSEOnlineRecord>();
-        private string mainDBConnectString;// = ConfigurationManager.ConnectionStrings["MainDBContext"].ToString();
-        private string onlineDBConnectString;// = ConfigurationManager.ConnectionStrings["OnlineLogDBContext"].ToString();
+        private readonly ILogger logger;
+        private readonly List<EVSEOnlineRecord> updateData = new List<EVSEOnlineRecord>();
+        private readonly List<EVSEOnlineRecord> insertData = new List<EVSEOnlineRecord>();
+        private readonly string mainDBConnectString;// = ConfigurationManager.ConnectionStrings["MainDBContext"].ToString();
+        private readonly string onlineDBConnectString;// = ConfigurationManager.ConnectionStrings["OnlineLogDBContext"].ToString();
+        private DateTime latestHeartbeatTime = DateTime.UtcNow;
 
         public CheckEVSEOnlineJob(IConfiguration configuration, ILogger<CheckEVSEOnlineJob> logger)
         {
@@ -44,7 +42,7 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
 
         public async Task Execute(IJobExecutionContext context)
         {
-            logger.LogDebug(this.ToString() + " :Starting........");
+            using var timer = TimerHelper.Start(this.ToString(), logger);
             try
             {
                 List<EVSECurrentStatus> _EVSEs = await GetEVSEs();
@@ -236,10 +234,7 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
                 logger.LogDebug("ERROR " + this.ToString() + ex.ToString());
             }
 
-
-
-            logger.LogDebug(this.ToString() + " :Finished........");
-
+            logger.LogInformation("{0} complete", this.ToString());
         }
 
 
@@ -251,9 +246,13 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
                 using (var dbConn = new SqlConnection(mainDBConnectString))
                 {
                     //dbConn.Open();
-                    string sqlstring = "SELECT m.CustomerId,m.Id,m.ChargeBoxId,m.Online,m.HeartbeatUpdatedOn,MachineConfigurations.ConfigureSetting HeartbeatInterval"
-                   + "  FROM [dbo].[Machine]  m  left join [dbo].[MachineConfigurations]  MachineConfigurations  on m.ChargeBoxId = MachineConfigurations.ChargeBoxId"
-                   + " where MachineConfigurations.ConfigureName = 'HeartbeatInterval'  and MachineConfigurations.ConfigureSetting!=''";
+                    string sqlstring = """
+                       SELECT m.CustomerId,m.Id,m.ChargeBoxId,m.Online,m.HeartbeatUpdatedOn,MachineConfigurations.ConfigureSetting HeartbeatInterval
+                       FROM [dbo].[Machine]  m  
+                       left join [dbo].[MachineConfigurations] MachineConfigurations  
+                       on m.ChargeBoxId = MachineConfigurations.ChargeBoxId
+                       where MachineConfigurations.ConfigureName = 'HeartbeatInterval' and MachineConfigurations.ConfigureSetting!=''
+                       """;
                     result = (await dbConn.QueryAsync<EVSECurrentStatus>(sqlstring)).ToList();
                 }
 
@@ -412,15 +411,9 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
 
         private void ClearCache()
         {
-            if (updateData != null)
-            {
-                updateData.Clear();
-            }
+            updateData?.Clear();
 
-            if (insertData != null)
-            {
-                insertData.Clear();
-            }
+            insertData?.Clear();
         }
 
 

+ 16 - 19
EVCB_OCPP.TaskScheduler/Jobs/CheckExecutionCmdJob.cs

@@ -1,4 +1,5 @@
-using EVCB_OCPP.TaskScheduler.Services;
+using EVCB_OCPP.TaskScheduler.Helper;
+using EVCB_OCPP.TaskScheduler.Services;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Logging;
 using Quartz;
@@ -13,45 +14,41 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
     [DisallowConcurrentExecution]
     public class CheckExecutionCmdJob : IJob
     {
-        private readonly IServiceProvider serviceProvider;
-        private ILogger logger;// = NLog.LogManager.GetCurrentClassLogger();
+        private readonly ICustomersService customersService;
+        private readonly ILogger logger;// = NLog.LogManager.GetCurrentClassLogger();
 
 
-        public CheckExecutionCmdJob(IServiceProvider serviceProvider)
+        public CheckExecutionCmdJob(ICustomersService customersService, ILogger<CheckExecutionCmdJob> logger)
         {
-            logger = serviceProvider.GetService<ILogger<CheckExecutionCmdJob>>();
-            this.serviceProvider = serviceProvider;
+            this.logger = logger;
+            this.customersService = customersService;
         }
 
 
         public async Task Execute(IJobExecutionContext context)
         {
-            await Console.Out.WriteLineAsync(this.ToString() + " :Starting........");
+            using var timer = TimerHelper.Start(this.ToString(), logger);
 
             List<Task> tList = new List<Task>();
 
-            ICustomerService cs = serviceProvider.GetService<ICustomerService>();//new CommonCustomerService();
-            var cList = cs.GetCallPartnerCustomers();
+            //ICustomersService cs = serviceProvider.GetService<ICustomersService>();//new CommonCustomerService();
+            var cList = customersService.GetCallPartnerCustomers();
 
             foreach (var customerId in cList)
             {
-                ICustomerService s = serviceProvider.GetService<ICustomerService>();//.Create(customerId);
-                await s.SetCustomerId(customerId);
+                ICustomerService s = await customersService.GetCustomerService(customerId);
 
-
-                tList.Add(Task.Run(() => DoMainTask(customerId)));
+                tList.Add(DoMainTask(s));
             }
 
-            Task.WaitAll(tList.ToArray());
+            await Task.WhenAll(tList.ToArray());
 
-            await Console.Out.WriteLineAsync(this.ToString() + " :Finished........");
+            logger.LogInformation("{0} complete", this.ToString());
         }
 
-        private void DoMainTask(Guid customerId)
+        private Task DoMainTask(ICustomerService customerService)
         {
-            ICustomerService _service = serviceProvider.GetService<ICustomerService>();//.Create(customerId);
-            _service.SetCustomerId(customerId).Wait();
-            _service.MonitorRemoteCommand().Wait();
+            return customerService.MonitorRemoteCommand();
         }
     }
 

+ 15 - 19
EVCB_OCPP.TaskScheduler/Jobs/ExecutionCmdReportJob.cs

@@ -1,4 +1,5 @@
-using EVCB_OCPP.TaskScheduler.Services;
+using EVCB_OCPP.TaskScheduler.Helper;
+using EVCB_OCPP.TaskScheduler.Services;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Logging;
 using Quartz;
@@ -13,45 +14,40 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
     [DisallowConcurrentExecution]
     public class ExecutionCmdReportJob : IJob
     {
-        private readonly IServiceProvider serviceProvider;
-        private ILogger logger;// = NLog.LogManager.GetCurrentClassLogger();
+        private readonly ICustomersService customersService;
+        private readonly ILogger logger;// = NLog.LogManager.GetCurrentClassLogger();
 
 
-        public ExecutionCmdReportJob(IServiceProvider serviceProvider)
+        public ExecutionCmdReportJob(ICustomersService customersService,ILogger<ExecutionCmdReportJob> logger)
         {
-            logger = serviceProvider.GetService<ILogger<ExecutionCmdReportJob>>();
-            this.serviceProvider = serviceProvider;
+            this.customersService = customersService;
+            this.logger = logger;
         }
 
 
         public async Task Execute(IJobExecutionContext context)
         {
-            await Console.Out.WriteLineAsync(this.ToString() + " :Starting........");
+            using var timer = TimerHelper.Start(this.ToString(), logger);
 
             List<Task> tList = new List<Task>();
 
-            ICustomerService cs = serviceProvider.GetService<ICustomerService>();//new CommonCustomerService();
-            var cList = cs.GetCallPartnerCustomers();
+            var cList = customersService.GetCallPartnerCustomers();
 
             foreach (var customerId in cList)
             {
-                ICustomerService s = serviceProvider.GetService<ICustomerService>();
-                await s.SetCustomerId(customerId);
+                ICustomerService s = await customersService.GetCustomerService(customerId);
 
-
-                tList.Add(Task.Run(() => DoMainTask(customerId)));
+                tList.Add(DoMainTask(s));
             }
 
-            Task.WaitAll(tList.ToArray());
+            await Task.WhenAll(tList.ToArray());
 
-            await Console.Out.WriteLineAsync(this.ToString() + " :Finished........");
+            logger.LogInformation("{0} complete", this.ToString());
         }
 
-        private void DoMainTask(Guid customerId)
+        private Task DoMainTask(ICustomerService _service)
         {
-            ICustomerService _service = serviceProvider.GetService<ICustomerService>();
-            _service.SetCustomerId(customerId).Wait();
-            _service.ReportExecutionofRemoteCommand().Wait();
+            return _service.ReportExecutionofRemoteCommand();
         }
     }
 }

+ 31 - 53
EVCB_OCPP.TaskScheduler/Jobs/JobScheduler.cs

@@ -1,4 +1,5 @@
-using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
 using Quartz;
 using System;
 using System.Collections.Generic;
@@ -10,84 +11,61 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
 {
     public static class JobScheduler
     {
-        public static void AddTaskSchedulerQuartz(this IServiceCollection services)
+        public static void AddTaskSchedulerQuartz(this IServiceCollection services, JobsConfig config)
         {
             services.AddQuartz(q => {
 
                 q.UseMicrosoftDependencyInjectionJobFactory();
 
-                var CheckEVSEOnlineJobKey = new JobKey("job1", "group1");
-                q.AddJob<CheckEVSEOnlineJob>(opts => { opts.WithIdentity(CheckEVSEOnlineJobKey); });
-
-                var StartTransacionReportJobKey = new JobKey("job2", "group1");
-                q.AddJob<StartTransacionReportJob>(opts => { opts.WithIdentity(StartTransacionReportJobKey); });
-
-                var StopTransacionReportJobKey = new JobKey("job3", "group1");
-                q.AddJob<StopTransacionReportJob>(opts => { opts.WithIdentity(StopTransacionReportJobKey); });
-
-                var CheckExecutionCmdJobKey = new JobKey("job4", "group1");
-                q.AddJob<CheckExecutionCmdJob>(opts => { opts.WithIdentity(CheckExecutionCmdJobKey); });
-
-                var ExecutionCmdReportJobKey = new JobKey("job5", "group1");
-                q.AddJob<ExecutionCmdReportJob>(opts => { opts.WithIdentity(ExecutionCmdReportJobKey); });
-
-                q.AddTrigger(opts =>
-                {
-                    opts
-                    .ForJob(CheckEVSEOnlineJobKey)
-                    .WithIdentity("trigger1", "group1")
+                q.ScheduleJob<CheckEVSEOnlineJob>(trigger =>
+                    trigger
+                    .WithIdentity("CheckEVSEOnlineJobTrigger")
                     .StartNow()
                     .WithSimpleSchedule(x => x
                         .WithIntervalInSeconds(10)
-                        .RepeatForever());
-                });
+                        .RepeatForever())
+                );
 
-                q.AddTrigger(opts =>
-                {
-                    opts
-                    .ForJob(StartTransacionReportJobKey)
-                    .WithIdentity("trigger2", "group1")
+                q.ScheduleJob<StartTransacionReportJob>(trigger =>
+                    trigger
+                    .WithIdentity("StartTransacionReportJobTrigger")
                     .StartNow()
                     .WithSimpleSchedule(x => x
                         .WithIntervalInSeconds(10)
-                        .RepeatForever());
-                });
+                        .RepeatForever())
+                );
 
-                q.AddTrigger(opts =>
-                {
-                    opts
-                    .ForJob(StopTransacionReportJobKey)
-                    .WithIdentity("trigger3", "group1")
+                q.ScheduleJob<StopTransacionReportJob>(trigger =>
+                    trigger
+                    .WithIdentity("StopTransacionReportJobTrigger")
                     .StartNow()
                     .WithSimpleSchedule(x => x
                         .WithIntervalInSeconds(10)
-                        .RepeatForever());
-                });
+                        .RepeatForever())
+                );
 
-                q.AddTrigger(opts =>
-                {
-                    opts
-                    .ForJob(CheckExecutionCmdJobKey)
-                    .WithIdentity("trigger4", "group1")
+                q.ScheduleJob<CheckExecutionCmdJob>(trigger =>
+                    trigger
+                    .WithIdentity("CheckExecutionCmdJobTrigger")
                     .StartNow()
                     .WithSimpleSchedule(x => x
                         .WithIntervalInSeconds(10)
-                        .RepeatForever());
-                });
+                        .RepeatForever())
+                );
 
-                q.AddTrigger(opts =>
-                {
-                    opts
-                    .ForJob(ExecutionCmdReportJobKey)
-                    .WithIdentity("trigger5", "group1")
+                q.ScheduleJob<ExecutionCmdReportJob>(trigger =>
+                    trigger
+                    .WithIdentity("ExecutionCmdReportJobTrigger")
                     .StartNow()
                     .WithSimpleSchedule(x => x
                         .WithIntervalInSeconds(10)
-                        .RepeatForever());
-                });
+                        .RepeatForever())
+                );
             });
 
-            services.AddQuartzHostedService();
+            services.AddQuartzHostedService(configure => {
+                configure.WaitForJobsToComplete = true;
+            });
         }
     }
 }

+ 16 - 0
EVCB_OCPP.TaskScheduler/Jobs/JobsConfig.cs

@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.TaskScheduler.Jobs;
+
+public class JobsConfig
+{
+    public bool EnableCheckEVSEOnlineJob { get; set; } = true;
+    public bool EnableStartTransacionReportJob { get; set; } = true;
+    public bool EnableStopTransacionReportJob { get; set; } = true;
+    public bool EnableCheckExecutionCmdJob { get; set; } = true;
+    public bool EnableExecutionCmdReportJob { get; set; } = true;
+}

+ 17 - 23
EVCB_OCPP.TaskScheduler/Jobs/StartTransacionReportJob.cs

@@ -1,4 +1,5 @@
-using EVCB_OCPP.TaskScheduler.Services;
+using EVCB_OCPP.TaskScheduler.Helper;
+using EVCB_OCPP.TaskScheduler.Services;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Logging;
 using Quartz;
@@ -13,48 +14,41 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
     [DisallowConcurrentExecution]
     public class StartTransacionReportJob : IJob
     {
-        private readonly IServiceProvider serviceProvider;
-        private ILogger logger;// = NLog.LogManager.GetCurrentClassLogger();
-     
+        private readonly ICustomersService customersService;
+        private readonly ILogger logger;
 
-        public StartTransacionReportJob(IServiceProvider serviceProvider)
+        public StartTransacionReportJob(ICustomersService customersService, ILogger<StartTransacionReportJob> logger )
         {
-            this.serviceProvider = serviceProvider;
-
-            logger = serviceProvider.GetService<ILogger<StartTransacionReportJob>>();
+            this.customersService = customersService;
+            this.logger = logger;
         }
       
 
         public async Task Execute(IJobExecutionContext context)
         {
-            await Console.Out.WriteLineAsync(this.ToString() + " :Starting........");
+            using var timer = TimerHelper.Start(this.ToString(), logger);
 
             List<Task> tList = new List<Task>();
 
-            ICustomerService cs = serviceProvider.GetService<ICustomerService>();// new CommonCustomerService();
-            var cList = cs.GetCallPartnerCustomers();
+            var cList = customersService.GetCallPartnerCustomers();
 
             foreach (var customerId in cList)
             {
-                ICustomerService s = serviceProvider.GetService<ICustomerService>();//.Create(customerId);
-                await s.SetCustomerId(customerId);
+                if (customerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8")) continue;
+
+                ICustomerService s = await customersService.GetCustomerService(customerId);
 
-               tList.Add(Task.Run(() => DoMainTask(customerId)));
+               tList.Add(DoMainTask(s));
             }
 
-            Task.WaitAll(tList.ToArray());
+            await Task.WhenAll(tList.ToArray());
 
-            await Console.Out.WriteLineAsync(this.ToString() + " :Finished........");
+            logger.LogInformation("{0} complete", this.ToString());
         }
 
-        private void DoMainTask(Guid customerId)
+        private Task DoMainTask(ICustomerService _service)
         {
-            if (customerId == new Guid("009E603C-79CD-4620-A2B8-D9349C0E8AD8")) return;
-
-
-            ICustomerService _service = serviceProvider.GetService<ICustomerService>();
-            _service.SetCustomerId(customerId).Wait();
-            _service.ReportStartTransaction().Wait();
+            return _service.ReportStartTransaction();
         }
     }
 }

+ 15 - 20
EVCB_OCPP.TaskScheduler/Jobs/StopTransacionReportJob.cs

@@ -1,4 +1,5 @@
-using EVCB_OCPP.TaskScheduler.Services;
+using EVCB_OCPP.TaskScheduler.Helper;
+using EVCB_OCPP.TaskScheduler.Services;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Logging;
 using Quartz;
@@ -13,46 +14,40 @@ namespace EVCB_OCPP.TaskScheduler.Jobs
     [DisallowConcurrentExecution]
     public class StopTransacionReportJob : IJob
     {
-        private readonly IServiceProvider serviceProvider;
-        private ILogger logger;// = NLog.LogManager.GetCurrentClassLogger();
+        private readonly ICustomersService customersService;
+        private readonly ILogger logger;
 
 
-        public StopTransacionReportJob(IServiceProvider serviceProvider)
+        public StopTransacionReportJob(ICustomersService customersService, ILogger<StopTransacionReportJob> logger)
         {
-            logger = serviceProvider.GetService<ILogger<StopTransacionReportJob>>();
-            this.serviceProvider = serviceProvider;
+            this.customersService = customersService;
+            this.logger = logger;
         }
 
 
         public async Task Execute(IJobExecutionContext context)
         {
-            logger.LogInformation(this.ToString() + " :Starting........");
+            using var timer = TimerHelper.Start(this.ToString(), logger);
 
             List<Task> tList = new List<Task>();
 
-            ICustomerService cs = serviceProvider.GetService<ICustomerService>();// new CommonCustomerService();
-            var cList = cs.GetNotifyStopTransactionCustomers();
+            var cList = customersService.GetNotifyStopTransactionCustomers();
 
             foreach (var customerId in cList)
             {
-                ICustomerService s = serviceProvider.GetService<ICustomerService>();//.Create(customerId);
-                await s.SetCustomerId(customerId);
+                ICustomerService s = await customersService.GetCustomerService(customerId);
 
-
-                tList.Add(Task.Run(() => DoMainTask(customerId)));
+                tList.Add(DoMainTask(s));
             }
 
-            Task.WaitAll(tList.ToArray());
+            await Task.WhenAll(tList.ToArray());
 
-            logger.LogInformation(this.ToString() + " :Finished........");
-            await Console.Out.WriteLineAsync(this.ToString() + " :Finished........");
+            logger.LogInformation("{0} complete", this.ToString());
         }
 
-        private void DoMainTask(Guid customerId)
+        private Task DoMainTask(ICustomerService _service)
         {
-            ICustomerService _service = serviceProvider.GetService<ICustomerService>();//.Create(customerId);
-            _service.SetCustomerId(customerId).Wait();
-            _service.ReportStopTransaction().Wait();
+           return _service.ReportStopTransaction();
         }
     }
 }

+ 2 - 2
EVCB_OCPP.TaskScheduler/OuterHttpClient.cs

@@ -18,9 +18,9 @@ namespace EVCB_OCPP.TaskScheduler
         private HttpClientService httpClient = new HttpClientService();
         private ILogger logger;// = NLog.LogManager.GetCurrentClassLogger();
 
-        public OuterHttpClient(IServiceProvider serviceProvider)
+        public OuterHttpClient(ILogger _logger)
         {
-            logger = serviceProvider.GetService<ILogger<OuterHttpClient>>();
+            _logger = logger;// serviceProvider.GetService<ILogger<OuterHttpClient>>();
         }
 
         async public Task<HttpResult> Post(string url, Dictionary<string, string> headers, string requestBody, string saltkey)

+ 7 - 4
EVCB_OCPP.TaskScheduler/Program.cs

@@ -1,6 +1,7 @@
 
 using EVCB_OCPP.TaskScheduler.Jobs;
 using EVCB_OCPP.TaskScheduler.Services;
+using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Hosting;
 using Microsoft.Extensions.Logging;
@@ -32,11 +33,13 @@ namespace EVCB_OCPP.TaskScheduler
                 .UseNLog()
                 .ConfigureServices((context, services) => {
 
-                    services.AddScoped<ICustomerService, CommonCustomerService>();
-                    services.AddScoped<DatabaseService>();
-                    services.AddScoped<OuterHttpClient>();
+                    services.AddTransient<ICustomerService, CommonCustomerService>();
+                    services.AddSingleton<ICustomersService, CustomersService>();
 
-                    services.AddTaskSchedulerQuartz();
+                    services.AddSingleton<DatabaseService>();
+                    //services.AddTransient<OuterHttpClient>();
+
+                    services.AddTaskSchedulerQuartz(context.Configuration.GetSection("Jobs").Get<JobsConfig>());
                     services.AddHostedService<TestService>();
                 })
                 .Build();

+ 12 - 22
EVCB_OCPP.TaskScheduler/Services/CommonCustomerService.cs

@@ -15,21 +15,22 @@ namespace EVCB_OCPP.TaskScheduler.Services
 {
     public class CommonCustomerService : ICustomerService
     {
-        private ILogger logger;
+        private readonly ILogger logger;
+        private readonly DatabaseService _dbService;// = new DatabaseService();
+        private readonly OuterHttpClient httpClient;//= new OuterHttpClient();
         private Guid customerId = Guid.Empty;
         private string customerName = string.Empty;
         private string _partnerAPIRoot = string.Empty;
         private string _saltkey = string.Empty;
         private CancellationToken _ct;
-        private DatabaseService _dbService;// = new DatabaseService();
         private ParallelOptions po = new ParallelOptions();
-        private OuterHttpClient httpClient;//= new OuterHttpClient();
         private int ChargeRecordCallCounter = 0;
 
-        public CommonCustomerService(IServiceProvider serviceProvider) { 
-            this.logger = serviceProvider.GetService<ILogger<CommonCustomerService>>();
-            this._dbService = serviceProvider.GetService<DatabaseService>();
-            this.httpClient = serviceProvider.GetService<OuterHttpClient>();
+        public CommonCustomerService(DatabaseService databaseService,ILoggerProvider loggerProvider)
+        {
+            this._dbService = databaseService;
+            this.logger = loggerProvider.CreateLogger(nameof(CommonCustomerService));
+            this.httpClient = new OuterHttpClient(loggerProvider.CreateLogger(nameof(OuterHttpClient)));
         }
 
         public async Task SetCustomerId(Guid customerId)
@@ -43,22 +44,11 @@ namespace EVCB_OCPP.TaskScheduler.Services
             _partnerAPIRoot = connectionInfo.ApiUrl;
         }
 
-        public List<Guid> GetCallPartnerCustomers()
-        {
-            return _dbService.GetCallParterAPICustomers();
-        }
-
-        public List<Guid> GetNotifyStopTransactionCustomers()
-        {
-            return _dbService.GetNotifyStopTransactionCustomers();
-        }
-
         async public Task ReportStartTransaction()
         {
             var items = await _dbService.GetNeedReportSession(customerId, true, 1000);
 
-            Stopwatch watch = new Stopwatch();
-            watch.Start();
+            Stopwatch watch = Stopwatch.StartNew();
 
             List<Task> groupTasks = new List<Task>();
             int skipCount = 0;
@@ -133,7 +123,7 @@ namespace EVCB_OCPP.TaskScheduler.Services
                             {
                                 sendBack.Add(r.Id, new TransactionResponse()
                                 {
-                                    StartTransactionReportedOn = DateTime.Now,
+                                    StartTransactionReportedOn = DateTime.UtcNow,
                                     ErrorMsg = response.Success ? null :
                                     (response.Exception == null ? response.Response : response.Exception.ToString())
                                 });
@@ -264,7 +254,7 @@ namespace EVCB_OCPP.TaskScheduler.Services
                                 {
                                     sendBack.Add(r.Id, new TransactionResponse()
                                     {
-                                        StopTransactionReportedOn = DateTime.Now,
+                                        StopTransactionReportedOn = DateTime.UtcNow,
                                         ErrorMsg = response.Success ? null :
                                         (response.Exception == null ? response.Response : response.Exception.ToString())
                                     });
@@ -394,7 +384,7 @@ namespace EVCB_OCPP.TaskScheduler.Services
                             {
                                 sendBack.Add(r.Id, new BasicResponse()
                                 {
-                                    ReportedOn = DateTime.Now,
+                                    ReportedOn = DateTime.UtcNow,
                                     ErrorMsg = response.Success ? null :
                                     (response.Exception == null ? response.Response : response.Exception.ToString())
                                 });                              

+ 0 - 24
EVCB_OCPP.TaskScheduler/Services/CustomerBackendFactory.cs

@@ -1,24 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace EVCB_OCPP.TaskScheduler.Services
-{
-    //public class CustomerBackendFactory
-    //{
-    //    private readonly IServiceProvider serviceProvider;
-
-    //    public CustomerBackendFactory(IServiceProvider serviceProvider) {
-    //        this.serviceProvider = serviceProvider;
-    //    }
-
-    //    public ICustomerService Create(Guid customerId)
-    //    {           
-    //        return new CommonCustomerService(customerId, serviceProvider);
-    //    }
-
-
-    //}
-}

+ 46 - 0
EVCB_OCPP.TaskScheduler/Services/CustomersService.cs

@@ -0,0 +1,46 @@
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace EVCB_OCPP.TaskScheduler.Services;
+
+public interface ICustomersService
+{
+    Task<ICustomerService> GetCustomerService(Guid guid); 
+    
+    List<Guid> GetNotifyStopTransactionCustomers();
+
+    List<Guid> GetCallPartnerCustomers();
+}
+
+public class CustomersService : ICustomersService
+{
+    private readonly IServiceProvider serviceProvider;
+    private readonly DatabaseService _dbService;
+
+    public CustomersService(IServiceProvider serviceProvider)
+    {
+        this.serviceProvider = serviceProvider; 
+        this._dbService = serviceProvider.GetService<DatabaseService>();
+    }
+
+    public async Task<ICustomerService> GetCustomerService(Guid guid)
+    {
+        var service = serviceProvider.GetRequiredService<ICustomerService>();
+        await service.SetCustomerId(guid);
+        return service;
+    }
+
+    public List<Guid> GetCallPartnerCustomers()
+    {
+        return _dbService.GetCallParterAPICustomers();
+    }
+
+    public List<Guid> GetNotifyStopTransactionCustomers()
+    {
+        return _dbService.GetNotifyStopTransactionCustomers();
+    }
+}

+ 1 - 1
EVCB_OCPP.TaskScheduler/Services/DatabaseService.cs

@@ -20,7 +20,7 @@ using Transaction = EVCB_OCPP.TaskScheduler.Models.Transaction;
 
 namespace EVCB_OCPP.TaskScheduler.Services
 {
-    internal class DatabaseService
+    public class DatabaseService
     {
         private ILogger logger;
         private readonly string mainDBConnectString;

+ 0 - 4
EVCB_OCPP.TaskScheduler/Services/ICustomerService.cs

@@ -10,10 +10,6 @@ namespace EVCB_OCPP.TaskScheduler.Services
     {
         Task SetCustomerId(Guid customerId);
 
-        List<Guid> GetNotifyStopTransactionCustomers();     
-        
-        List<Guid> GetCallPartnerCustomers();
-
         Task ReportStartTransaction();
 
         Task ReportStopTransaction();