【如何在ASP.Net Core中使用 IHostedService的方法】执行自动服务运行
1.首先再服务层创建一个服务 MyFirstHostedService
csharp
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace HostedServicesApp
{
public class MyFirstHostedService : BackgroundService
{
protected async override Task ExecuteAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
await Log();
await Task.Delay(1000, token);
}
}
private async Task Log()
{
using (StreamWriter sw = new StreamWriter(@"D:\log.txt",true))
{
await sw.WriteLineAsync(DateTime.Now.ToLongTimeString());
}
}
}
}
2.需要在.net core的Startup类文件中将刚刚创建的服务进行注册即可
具体如下:
csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<MyFirstHostedService>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
即可就实现了,即使当前是一个api接口,也可以实现自动执行某项任务
结果如下:
