- 'HostedService' - timed with TimeProvider.Timer . . . best choice for Unit Tests
- 'HostedService' - timed with Timer
- 'Worker' - timed with Task.Delay
- 'Worker' - timed with PeriodicTimer
This kind of Hosted Service enables Unit Testing without delays.
Therefore the Unit Tests can run much faster without having to wait.
- Create your Timers with 'timeProvider.CreateTimer(...)' instead of 'new Timer(...)'.
- For Unit Tests simply install NuGet package 'Microsoft.Extensions.TimeProvider.Testing'.
- Then inject Microsoft.Extensions.Time.Testing.FakeTimeProvider instead of TimeProvider.System.
- Now you can change the time within your unit tests for example with fakeTimeProvider.Advance(timespan).
A traditional Timer is not perfect for unit tests.
Task.Delay is not perfect for unit tests.
A PeriodicTimer is not perfect for unit tests.