Guest User

Untitled

a guest
Nov 14th, 2018
393
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. internal class TimedHostedService : IHostedService, IDisposable
  2. {
  3. private readonly ILogger _logger;
  4. private Timer _timer;
  5.  
  6. public TimedHostedService(ILogger<TimedHostedService> logger)
  7. {
  8. _logger = logger;
  9. }
  10.  
  11. public Task StartAsync(CancellationToken cancellationToken)
  12. {
  13. _logger.LogInformation("Timed Background Service is starting.");
  14.  
  15. _timer = new Timer(DoWork, null, TimeSpan.Zero,
  16. TimeSpan.FromSeconds(5));
  17.  
  18. return Task.CompletedTask;
  19. }
  20.  
  21. private void DoWork(object state)
  22. {
  23. _logger.LogInformation("Timed Background Service is working.");
  24. }
  25.  
  26. public Task StopAsync(CancellationToken cancellationToken)
  27. {
  28. _logger.LogInformation("Timed Background Service is stopping.");
  29.  
  30. _timer?.Change(Timeout.Infinite, 0);
  31.  
  32. return Task.CompletedTask;
  33. }
  34.  
  35. public void Dispose()
  36. {
  37. _timer?.Dispose();
  38. }
  39. }
  40.  
  41. public void ConfigureServices(IServiceCollection services)
  42. {
  43. ...
  44. services.AddHostedService<TimedHostedService>();
  45. ...
  46. }
Add Comment
Please, Sign In to add comment