Popular blog tags

一、asp.net core 简单定时任务,用BackgroundService实现 

public class TimedBackgroundService : BackgroundService
{
    private readonly ILogger _logger;
    private Timer _timer;

    public TimedBackgroundService(ILogger<TimedBackgroundService> logger)
    {
        _logger = logger;
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        _logger.LogInformation($"Hello World! - {DateTime.Now}");
    }

    public override void Dispose()
    {
        base.Dispose();
        _timer?.Dispose();
    }
}

在 ASP.NET Core Web 程序中执行这个后台定时任务只需在 Startup 的 ConfigureServices 注册 TimedBackgroundService 即可:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHostedService<TimedBackgroundService>();
}

然后只要站点启动,就会定时输出日志:

Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
      Hello World! - 9/14/2018 17:48:02
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
      Hello World! - 9/14/2018 17:48:07
info: BackgroundServiceSample.Services.TimedBackgroundService[0]
      Hello World! - 9/14/2018 17:48:12