Skip to content

Instantly share code, notes, and snippets.

@iqan
Last active April 16, 2019 10:34
Show Gist options
  • Save iqan/c3ddbf8b82c9cf0fc168adc5edfca125 to your computer and use it in GitHub Desktop.
Save iqan/c3ddbf8b82c9cf0fc168adc5edfca125 to your computer and use it in GitHub Desktop.
public class TimedHostedService : IHostedService, IDisposable
{
private readonly ILogger _logger;
private Timer _timer;
public TimedHostedService(ILogger<TimedHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Service is starting.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object state)
{
_logger.LogInformation("Service is running.");
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment