Windows Services and Worker Services
44.1 Worker Service (.NET)
Imports Microsoft.Extensions.Hosting
Imports Microsoft.Extensions.Logging
Imports Microsoft.Extensions.DependencyInjection
Public Class FileProcessorWorker
Inherits BackgroundService
Private ReadOnly _logger As ILogger(Of FileProcessorWorker)
Public Sub New(logger As ILogger(Of FileProcessorWorker))
_logger = logger
End Sub
Protected Overrides Async Function ExecuteAsync(stoppingToken As Threading.CancellationToken) As Task
While Not stoppingToken.IsCancellationRequested
_logger.LogInformation("Checking inbox at {time}", DateTimeOffset.Now)
' process files...
Await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken)
End While
End Function
End Class
Module Program
Sub Main(args As String())
Host.CreateDefaultBuilder(args).
UseWindowsService(). ' Microsoft.Extensions.Hosting.WindowsServices
ConfigureServices(Sub(ctx, services) services.AddHostedService(Of FileProcessorWorker)()).
Build().
Run()
End Sub
End Modulesc create MyVbService binPath= "C:\Services\MyVbService.exe" start= auto
sc start MyVbService44.2 Classic Windows Service (.NET Framework)
Inherits ServiceBase, override OnStart/OnStop, add an installer (ProjectInstaller), install with installutil.exe.
44.3 Scheduled Tasks and Background Jobs
Windows Task Scheduler running a console app, Quartz.NET or Hangfire for job scheduling, PeriodicTimer in worker services.