托管服务1\1.txt
this is a test file
托管服务1\appsettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
托管服务1\appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
托管服务1\DemoBgService.cs
public class DemoBgService : BackgroundService
{
private ILogger<DemoBgService> logger;
private Timer? timer; // 定义一个定时器字段
public DemoBgService(ILogger<DemoBgService> logger)
{
this.logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// 创建一个定时器,指定回调方法,延迟 5 秒开始,每隔 2 秒执行一次
timer = new Timer(ReadFile!, null, 5000, 2000);
}
// 定义一个回调方法,用于读取文件并记录日志
private async void ReadFile(object state)
{
logger.LogInformation($"{DateTime.Now}");
}
public override void Dispose()
{
base.Dispose();
// 释放定时器资源
timer.Dispose();
}
}
托管服务1\Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHostedService<DemoBgService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
托管服务1\WeatherForecast.cs
namespace 托管服务1
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}
托管服务1\托管服务1.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
</Project>
托管服务1\Controllers\WeatherForecastController.cs
using Microsoft.AspNetCore.Mvc;
namespace 托管服务1.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}