Skip to content

Commit

Permalink
功能优化
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhangYiQiu committed Sep 13, 2024
1 parent 16fa1c0 commit 24bff22
Show file tree
Hide file tree
Showing 12 changed files with 47 additions and 83 deletions.
56 changes: 10 additions & 46 deletions src/TokenPay/BgServices/BaseBackgroundService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,61 +3,25 @@

namespace TokenPay.BgServices
{
public abstract class BaseBackgroundService : IHostedService, IDisposable
public abstract class BaseBackgroundService : BackgroundService
{
private Task? _executingTask;
protected readonly string? jobName;
protected readonly ILogger? __logger;
private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource();

protected BaseBackgroundService()
{
}
protected readonly string jobName;
protected readonly ILogger _logger;
protected BaseBackgroundService(string JobName, ILogger logger)
{
__logger = logger;
_logger = logger;
jobName = JobName;
}
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);

public virtual Task StartAsync(CancellationToken cancellationToken)
{
if (jobName != null && __logger != null)
__logger.LogInformation("Background Service {JobName} is starting.", jobName);

_executingTask = ExecuteAsync(_stoppingCts.Token);

if (_executingTask.IsCompleted)
{
return _executingTask;
}

return Task.CompletedTask;
}

public virtual async Task StopAsync(CancellationToken cancellationToken)
public override Task StartAsync(CancellationToken cancellationToken)
{
if (_executingTask == null)
{
return;
}

try
{
if (jobName != null && __logger != null)
__logger.LogInformation("Background Service {JobName} is stopping.", jobName);
_stoppingCts.Cancel();
}
finally
{
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
}

_logger.LogInformation("Background Service {JobName} is starting.", jobName);
return base.StartAsync(cancellationToken);
}

public virtual void Dispose()
public override Task StopAsync(CancellationToken cancellationToken)
{
_stoppingCts.Cancel();
_logger.LogInformation("Background Service {JobName} is stopping.", jobName);
return base.StartAsync(cancellationToken);
}
}

Expand Down
48 changes: 32 additions & 16 deletions src/TokenPay/BgServices/BaseScheduledService.cs
Original file line number Diff line number Diff line change
@@ -1,37 +1,53 @@
using System;

namespace TokenPay.BgServices
{
public abstract class BaseScheduledService : BackgroundService
{
protected readonly string jobName;
protected readonly ILogger Logger;
private readonly PeriodicTimer _timer;
private readonly TimeSpan period;
protected readonly ILogger _logger;
private PeriodicTimer? _timer;

protected BaseScheduledService(string JobName, TimeSpan period, ILogger logger)
{
Logger = logger;
_logger = logger;
jobName = JobName;
_timer = new PeriodicTimer(period);
this.period = period;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Logger.LogInformation("Service {JobName} is starting.", jobName);
do
_logger.LogInformation("Service {JobName} is starting.", jobName);
await Task.Delay(3000);//延迟3秒再启动任务
_timer = new PeriodicTimer(period);
try
{
try
do
{
await ExecuteAsync(DateTime.Now, stoppingToken);
}
catch (Exception ex)
{
Logger.LogError(ex, $"定时任务[{jobName}]执行出现错误");
}
} while (!stoppingToken.IsCancellationRequested && await _timer.WaitForNextTickAsync(stoppingToken));
try
{
await ExecuteAsync(DateTime.Now, stoppingToken);
}
catch (Flurl.Http.FlurlHttpException ex) when (ex.StatusCode == 401 || ex.StatusCode == 403)
{
_logger.LogError(ex, "定时任务[{jobName}]执行Api请求出现错误,返回:{code},通常为Api鉴权出现问题或者调用次数超出限制", jobName, ex.StatusCode);
}
catch (Exception ex)
{
_logger.LogError(ex, $"定时任务[{jobName}]执行出现错误");
}
} while (!stoppingToken.IsCancellationRequested && await _timer.WaitForNextTickAsync(stoppingToken));
}
catch (OperationCanceledException)
{
_logger.LogInformation("Service {JobName} has been cancelled.", jobName);
}
}
protected abstract Task ExecuteAsync(DateTime RunTime, CancellationToken stoppingToken);
public override Task StopAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("Service {JobName} is stopping.", jobName);
_timer.Dispose();
_logger.LogInformation("Service {JobName} is stopping.", jobName);
_timer?.Dispose();
return base.StopAsync(cancellationToken);
}
}
Expand Down
2 changes: 0 additions & 2 deletions src/TokenPay/BgServices/CollectionTRONService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public class CollectionTRONService : BaseScheduledService
private readonly IConfiguration _configuration;
private readonly TelegramBot _bot;
private readonly IFreeSql freeSql;
private readonly ILogger<CollectionTRONService> _logger;
/// <summary>
/// 是否启用归集功能
/// </summary>
Expand Down Expand Up @@ -67,7 +66,6 @@ public CollectionTRONService(
ILogger<CollectionTRONService> logger) : base("TRON归集任务", TimeSpan.FromHours(configuration.GetValue("Collection:CheckTime", 1)), logger)

Check warning on line 66 in src/TokenPay/BgServices/CollectionTRONService.cs

View workflow job for this annotation

GitHub Actions / Build And Publish

Using member 'Microsoft.Extensions.Configuration.ConfigurationBinder.GetValue<T>(IConfiguration, String, T)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.

Check warning on line 66 in src/TokenPay/BgServices/CollectionTRONService.cs

View workflow job for this annotation

GitHub Actions / Build And Publish

Using member 'Microsoft.Extensions.Configuration.ConfigurationBinder.GetValue<T>(IConfiguration, String, T)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.
{
this._configuration = configuration;
this._logger = logger;
this._bot = bot;
this.freeSql = freeSql;
}
Expand Down
2 changes: 0 additions & 2 deletions src/TokenPay/BgServices/OrderCheckEVMBaseService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ namespace TokenPay.BgServices
{
public class OrderCheckEVMBaseService : BaseScheduledService
{
private readonly ILogger<OrderCheckEVMBaseService> _logger;
private readonly IConfiguration _configuration;
private readonly IHostEnvironment _env;
private readonly Channel<TokenOrders> _channel;
Expand All @@ -26,7 +25,6 @@ public OrderCheckEVMBaseService(ILogger<OrderCheckEVMBaseService> logger,
List<EVMChain> Chains,
IFreeSql freeSql) : base("ETH订单检测", TimeSpan.FromSeconds(15), logger)
{
_logger = logger;
this._configuration = configuration;
this._env = env;
this._channel = channel;
Expand Down
2 changes: 0 additions & 2 deletions src/TokenPay/BgServices/OrderCheckEVMERC20Service.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ namespace TokenPay.BgServices
{
public class OrderCheckEVMERC20Service : BaseScheduledService
{
private readonly ILogger<OrderCheckEVMERC20Service> _logger;
private readonly IConfiguration _configuration;
private readonly IHostEnvironment _env;
private readonly List<EVMChain> _chains;
Expand All @@ -27,7 +26,6 @@ public OrderCheckEVMERC20Service(ILogger<OrderCheckEVMERC20Service> logger,
Channel<TokenOrders> channel,
IFreeSql freeSql) : base("ERC20订单检测", TimeSpan.FromSeconds(15), logger)
{
_logger = logger;
this._configuration = configuration;
this._env = env;
_chains = Chains;
Expand Down
4 changes: 1 addition & 3 deletions src/TokenPay/BgServices/OrderCheckTRC20Service.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ namespace TokenPay.BgServices
{
public class OrderCheckTRC20Service : BaseScheduledService
{
private readonly ILogger<OrderCheckTRC20Service> _logger;
private readonly IConfiguration _configuration;
private readonly IHostEnvironment _env;
private readonly Channel<TokenOrders> _channel;
Expand All @@ -25,7 +24,6 @@ public OrderCheckTRC20Service(ILogger<OrderCheckTRC20Service> logger,
Channel<TokenOrders> channel,
IFreeSql freeSql) : base("TRC20订单检测", TimeSpan.FromSeconds(3), logger)
{
_logger = logger;
this._configuration = configuration;
this._env = env;
this._channel = channel;
Expand Down Expand Up @@ -78,7 +76,7 @@ protected override async Task ExecuteAsync(DateTime RunTime, CancellationToken s
.SetQueryParams(query)
.WithTimeout(15);
if (_env.IsProduction())
req = req.WithHeader("TRON-PRO-API-KEY", _configuration.GetValue("TRON-PRO-API-KEY", ""));
req = req.WithHeader("TRON-PRO-API-KEY", _configuration.GetValue<string>("TRON-PRO-API-KEY"));

Check warning on line 79 in src/TokenPay/BgServices/OrderCheckTRC20Service.cs

View workflow job for this annotation

GitHub Actions / Build And Publish

Using member 'Microsoft.Extensions.Configuration.ConfigurationBinder.GetValue<T>(IConfiguration, String)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.
var result = await req
.GetJsonAsync<BaseResponse<TronTransaction>>();

Expand Down
4 changes: 1 addition & 3 deletions src/TokenPay/BgServices/OrderCheckTRXService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ namespace TokenPay.BgServices
{
public class OrderCheckTRXService : BaseScheduledService
{
private readonly ILogger<OrderCheckTRXService> _logger;
private readonly IConfiguration _configuration;
private readonly IHostEnvironment _env;
private readonly Channel<TokenOrders> _channel;
Expand All @@ -25,7 +24,6 @@ public OrderCheckTRXService(ILogger<OrderCheckTRXService> logger,
Channel<TokenOrders> channel,
IFreeSql freeSql) : base("TRX订单检测", TimeSpan.FromSeconds(3), logger)
{
_logger = logger;
this._configuration = configuration;
this._env = env;
this._channel = channel;
Expand Down Expand Up @@ -75,7 +73,7 @@ protected override async Task ExecuteAsync(DateTime RunTime, CancellationToken s
.SetQueryParams(query)
.WithTimeout(15);
if (_env.IsProduction())
req = req.WithHeader("TRON-PRO-API-KEY", _configuration.GetValue("TRON-PRO-API-KEY", ""));
req = req.WithHeader("TRON-PRO-API-KEY", _configuration.GetValue<string>("TRON-PRO-API-KEY"));

Check warning on line 76 in src/TokenPay/BgServices/OrderCheckTRXService.cs

View workflow job for this annotation

GitHub Actions / Build And Publish

Using member 'Microsoft.Extensions.Configuration.ConfigurationBinder.GetValue<T>(IConfiguration, String)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. In case the type is non-primitive, the trimmer cannot statically analyze the object's type so its members may be trimmed.
var result = await req
.GetJsonAsync<BaseResponse<TrxTransaction>>();

Expand Down
2 changes: 0 additions & 2 deletions src/TokenPay/BgServices/OrderExpiredService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@ namespace TokenPay.BgServices
{
public class OrderExpiredService : BaseScheduledService
{
private readonly ILogger<OrderExpiredService> _logger;
private readonly IConfiguration _configuration;
private readonly IFreeSql freeSql;

public OrderExpiredService(ILogger<OrderExpiredService> logger,
IConfiguration configuration,
IFreeSql freeSql) : base("订单过期", TimeSpan.FromSeconds(10), logger)
{
_logger = logger;
this._configuration = configuration;
this.freeSql = freeSql;
}
Expand Down
2 changes: 0 additions & 2 deletions src/TokenPay/BgServices/OrderNotifyService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ namespace TokenPay.BgServices
{
public class OrderNotifyService : BaseScheduledService
{
private readonly ILogger<OrderNotifyService> _logger;
private readonly IConfiguration _configuration;
private readonly IFreeSql freeSql;
private readonly FlurlClient client;
Expand All @@ -17,7 +16,6 @@ public OrderNotifyService(ILogger<OrderNotifyService> logger,
IConfiguration configuration,
IFreeSql freeSql) : base("订单通知", TimeSpan.FromSeconds(3), logger)
{
_logger = logger;
this._configuration = configuration;
this.freeSql = freeSql;
client = new FlurlClient();
Expand Down
2 changes: 0 additions & 2 deletions src/TokenPay/BgServices/OrderPaySuccessService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ public class OrderPaySuccessService : BaseBackgroundService
private readonly TelegramBot _bot;
private readonly List<EVMChain> _chain;
private readonly IConfiguration _configuration;
private readonly ILogger<OrderPaySuccessService> _logger;

public OrderPaySuccessService(
Channel<TokenOrders> channel,
Expand All @@ -28,7 +27,6 @@ public OrderPaySuccessService(
this._bot = bot;
this._chain = chain;
this._configuration = configuration;
this._logger = logger;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
Expand Down
2 changes: 0 additions & 2 deletions src/TokenPay/BgServices/UpdateRateService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public class UpdateRateService : BaseScheduledService
private readonly IConfiguration _configuration;
private readonly List<EVMChain> _chain;
private readonly IFreeSql freeSql;
private readonly ILogger<UpdateRateService> _logger;
private FiatCurrency BaseCurrency => Enum.Parse<FiatCurrency>(_configuration.GetValue("BaseCurrency", "CNY")!);
public UpdateRateService(
IConfiguration configuration,
Expand All @@ -28,7 +27,6 @@ public UpdateRateService(
this._configuration = configuration;
this._chain = chain;
this.freeSql = freeSql;
this._logger = logger;
}

private List<string> GetActiveCurrency()
Expand Down
4 changes: 3 additions & 1 deletion src/TokenPay/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Flurl.Http.Newtonsoft;
using FreeSql;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Data.Sqlite;
using Serilog;
using Serilog.Events;
using System.Diagnostics;
Expand Down Expand Up @@ -72,8 +73,9 @@

var connectionString = Configuration.GetConnectionString("DB");
IFreeSql fsql = new FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, connectionString)
.UseConnectionString(DataType.Sqlite, connectionString)
.UseAutoSyncStructure(true) //自动同步实体结构
.UseAdoConnectionPool(true)
.UseNoneCommandParameter(true)
.Build();

Expand Down

0 comments on commit 24bff22

Please sign in to comment.