1+ using System ;
2+ using System . Text . Json ;
3+ using System . Threading ;
4+ using System . Threading . Tasks ;
5+ using System . Timers ;
6+ using Microsoft . Extensions . Configuration ;
7+ using Microsoft . Extensions . Hosting ;
8+ using Microsoft . Extensions . Logging ;
9+ using Microsoft . Extensions . Options ;
10+ using Stravaig . Configuration . Diagnostics . Logging ;
11+ using Timer = System . Timers . Timer ;
12+
13+
14+ namespace Example ;
15+
16+ public class TheHostedService : IHostedService , IDisposable
17+ {
18+ private readonly ILogger < TheHostedService > _logger ;
19+ private readonly IConfigurationRoot _configRoot ;
20+ private readonly IOptions < MyFeatureConfiguration > _featureValues ;
21+ private readonly Timer _timer ;
22+
23+ public TheHostedService (
24+ ILogger < TheHostedService > logger ,
25+ IConfigurationRoot configRoot ,
26+ IOptions < MyFeatureConfiguration > featureValues )
27+ {
28+ _logger = logger ;
29+ _configRoot = configRoot ;
30+ _featureValues = featureValues ;
31+ _timer = new Timer ( 10000 ) ;
32+ _timer . Elapsed += TimerOnElapsed ;
33+ }
34+
35+ private void TimerOnElapsed ( object ? sender , ElapsedEventArgs e )
36+ {
37+ var jsonOptions = new JsonSerializerOptions ( )
38+ {
39+ WriteIndented = true ,
40+ } ;
41+ string json = JsonSerializer . Serialize ( _featureValues . Value , jsonOptions ) ;
42+ Console . Clear ( ) ;
43+ _logger . LogInformation (
44+ "At {Time} the object looks like:\n {Json}" ,
45+ e . SignalTime ,
46+ json ) ;
47+ _logger . LogConfigurationValuesAsInformation ( _configRoot . GetSection ( "MyConfiguration" ) ) ;
48+ }
49+
50+ public Task StartAsync ( CancellationToken cancellationToken )
51+ {
52+ _logger . LogInformation ( "The hosted service is starting." ) ;
53+ _logger . LogProvidersAsInformation ( _configRoot ) ;
54+ _timer . Enabled = true ;
55+ return Task . CompletedTask ;
56+ }
57+
58+ public Task StopAsync ( CancellationToken cancellationToken )
59+ {
60+ _timer . Enabled = false ;
61+ _logger . LogInformation ( "The hosted service is ending." ) ;
62+ return Task . CompletedTask ;
63+ }
64+
65+ public void Dispose ( )
66+ {
67+ _timer . Dispose ( ) ;
68+ }
69+ }
0 commit comments