net core-调用接口方式实现IHostedService的停止和启动

发布时间 2023-05-31 10:23:34作者: 斯蒂芬斯

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

[Route("home")]
[AllowAnonymous]
public class HomeController : ControllerBase {
 private readonly IEnumerable<IHostedService> _hostedServices;
 private readonly RecureHostedService _recureHostedService;

 public HomeController(IEnumerable<IHostedService> hostedServices)
 {
     //_recureHostedService = hostedService;// as RecureHostedService;
     // var hosteds = services.BuildServiceProvider().GetServices<IHostedService>();
     _hostedServices = hostedServices;
     _recureHostedService = _hostedServices.First(t => t is RecureHostedService) as RecureHostedService;
 }
 
[Route("About")]
 public IActionResult About()
 {
     //ViewData["Message"] = "Your application description page.";
     _recureHostedService.StopAsync(new System.Threading.CancellationToken());
     return Ok("Hello from Recure.");
 }
 [Route("Contact")]
 public IActionResult Contact()
 {
     // ViewData["Message"] = "Your contact page.";
     _recureHostedService.StartAsync(new System.Threading.CancellationToken());
     return Ok("Your contact page.");
 } }

public class RecureHostedService : IHostedService, IDisposable
 {
private readonly ILogger _log;
private Timer _timer;
public RecureHostedService(ILogger<RecureHostedService> log)
{
    _log = log;
}

public void Dispose()
{
    _timer.Dispose();
}

public Task StartAsync(CancellationToken cancellationToken)
{
    _log.LogInformation("RecureHostedService is Starting");
    _timer = new Timer(DoWork,null,TimeSpan.Zero, TimeSpan.FromSeconds(5));
    return Task.CompletedTask;
}

public Task StopAsync(CancellationToken cancellationToken)
{
    _log.LogInformation("RecureHostedService is Stopping");
    _timer?.Change(Timeout.Infinite, 0);
    return Task.CompletedTask;
}
private void DoWork(object state)
{
    _log.LogInformation("Timed Background Service is working.");
}
}

在program.cs中:

builder.Services.AddSingleton<IHostedService, RecureHostedService>();