【如何在ASP.Net Core中使用 IHostedService的方法】执行自动服务运行

如何在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接口,也可以实现自动执行某项任务

结果如下:

相关推荐
Apifox3 分钟前
Apifox 6 月更新|Apifox CLI 全面升级、导入导出优化、OAuth 2.0 支持自动刷新令牌
前端·后端·测试
悟空瞎说16 分钟前
NestJS 接口设计避坑:摒弃万能用户更新接口,落地单一职责与最小权限原则
后端·nestjs
smallyoung20 分钟前
Spring AI 2.0 VectorStore实战:从原理到RAG落地
人工智能·后端
jiayou6427 分钟前
KingbaseES 表级与列级加密完全指南
数据库·后端
青丘27 分钟前
Spring AI整合Milvus向量数据库实战
后端
古茗前端团队2 小时前
急招!前端|测试|后端|产品(名额多,速来)
前端·后端·架构
喵个咪3 小时前
Go-Wind HTTP 服务器从入门到精通
后端·http·go
hunterandroid3 小时前
Hilt 依赖注入:从手动 new 到自动装配
后端