1- using System ;
1+ using System ;
22using System . Collections . Generic ;
33using System . Threading ;
44using System . Threading . Tasks ;
@@ -15,6 +15,7 @@ public abstract class TimedHostedService : BackgroundService {
1515 private readonly int interval ;
1616 private readonly bool enabled ;
1717 private readonly bool generateCorrelationId ;
18+ protected DateTime lastActivity = DateTime . UtcNow ;
1819
1920 /// <summary>
2021 /// Initializes new instance of the Hosted Service
@@ -28,17 +29,19 @@ protected TimedHostedService(ILogger logger, bool enabled, int interval, bool ge
2829
2930 protected override async Task ExecuteAsync ( CancellationToken stoppingToken ) {
3031 // force async so that hosted service does not block Startup
31- #pragma warning disable _MissingConfigureAwait // Consider using .ConfigureAwait(false).
3232 await Task . Yield ( ) ;
33- #pragma warning restore _MissingConfigureAwait // Consider using .ConfigureAwait(false).
3433
3534 if ( enabled ) {
3635 logger . LogInformation ( $ "{ this . GetType ( ) . Name } is starting with interval of { interval } seconds") ;
37-
3836 stoppingToken . Register ( ( ) => logger . LogDebug ( $ "{ this . GetType ( ) . Name } is stopping.") ) ;
3937
4038 while ( ! stoppingToken . IsCancellationRequested ) {
39+ // last execution set before and after interval to catch start and catch after sleep delay
40+ lastActivity = DateTime . UtcNow ;
41+
4142 await IntervalAsync ( ) ;
43+ lastActivity = DateTime . UtcNow ;
44+
4245 await Task . Delay ( TimeSpan . FromSeconds ( interval ) , stoppingToken ) . ConfigureAwait ( false ) ;
4346 }
4447 logger . LogInformation ( $ "{ this . GetType ( ) . Name } is stopping") ;
@@ -61,5 +64,15 @@ private async Task IntervalAsync() {
6164 }
6265
6366 protected abstract Task ExecuteIntervalAsync ( ) ;
67+
68+ /// <summary>
69+ /// Last activity time for purposes of being able to monitor health
70+ /// </summary>
71+ public DateTime LastActivity => lastActivity ;
72+
73+ /// <summary>
74+ /// Sleep delay/interval between executions
75+ /// </summary>
76+ public TimeSpan Interval => TimeSpan . FromSeconds ( interval ) ;
6477 }
6578}
0 commit comments