I understand you’re open to options, so follow one more:
Topshelf
It creates a very simple environment to create Windows Services with timers.
Just install Topshelf Nuget Package in your project Console Application
:
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");
});
}
}
Then create the container that will fire and control the lifecycle 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 life cycle. Can pause, stop and restart from the Windows service panel - or left from anywhere else that can manage services.
See more details in this article on how to create Windows Service with Topshelf.
Official website Topshelf.
Is using some database?
– Randrade
Yes, I use SQL Server
– João Pedro Silva
See if that answer helps you. With the Hangfire you can make a function run in the background with the time you want.
– Randrade
@Randrade in his case will not be possible to use Hangfire, unfortunately the
Recurring jobs
gets aCRON schedule
to set the time, and the shortest range that can be set using a CRON is 1 minute.– Tobias Mesquita
@Tobymosque It depends on the shape he wants to use. You can set the 10 seconds as the time he searches for the Jobs in the bank, and not by CRON. If that’s all there is to it.
– Randrade
@Tobymosque It is worth remembering that their github already have some issues for this issue.
– Randrade
You should be careful with the Timer as it will run every 10 seconds regardless of whether the last process is over or not.
– lcssanches