I understand you're open to options, so here's one more:
TopShelf
It creates a very simple environment for creating Windows Services with timers.
Just install TopShelf NuGet Package in your Console Application
project:
Install-Package Topshelf
Then, in a very elegant way, create your service:
public class Program
{
public static void Main(string[] args)
{
HostFactory.Run(configurator =>
{
configurator.Service<MeuServicoPeriodico>(s =>
{
s.ConstructUsing(name => new MeuServicoPeriodico());
s.WhenStarted((service, control) => service.Start(control));
s.WhenStopped((service, control) => service.Stop(control));
});
configurator.RunAsLocalSystem();
configurator.SetDescription("Sobre meu serviço periódico");
});
}
}
Next, create the container that will trigger and control the life cycle of your service:
public sealed class MeuServicoPeriodico: ServiceControl
{
private readonly CancellationTokenSource _cancellationTokenSource;
public MeuServicoPeriodico()
{
_cancellationTokenSource = new CancellationTokenSource();
}
public bool Start(HostControl hostControl)
{
Task.Run(() =>
{
while (true)
{
// Funções do seu aplicativo vão aqui
Thread.Sleep(TimeSpan.FromSeconds(5));
}
}, _cancellationTokenSource.Token);
return true;
}
public bool Stop(HostControl hostControl)
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
return true;
}
}
Yes, it uses the "concept" of while-true-sleep
, but this loop is in a task where your service has full control over its lifecycle. You can pause, stop, and restart from the Windows services panel - or from anywhere else you can manage service.
See more details in this article on creating Windows Service with TopShelf .
Official site TopShelf .