-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrintTextToConsoleService.cs
48 lines (42 loc) · 1.37 KB
/
PrintTextToConsoleService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SimpleHostingConsole
{
internal class PrintTextToConsoleService : IHostedService, IDisposable
{
private ILogger Logger { get; }
private IOptions<AppConfig> AppConfig { get; }
private Timer _timer;
public PrintTextToConsoleService(ILogger<PrintTextToConsoleService> logger, IOptions<AppConfig> appConfig)
{
Logger = logger;
AppConfig = appConfig;
}
public void Dispose()
{
_timer?.Dispose();
}
public Task StartAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("Starting...");
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
Logger.LogInformation("Stopping");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
private void DoWork(object state)
{
Logger.LogInformation($"Background work with text: {AppConfig.Value.TextToPrint}");
}
}
}