I could just write a long-running CLI app and run it, but I\'m assuming it wouldn\'t comply to all the expectations one would have of a standards-compliant linux daemon (respond
Implementing Linux Daemon or service for windows
quite easy with single codebase using Visual Studio 2019. Just create project using WorkerService
template. In my case I have
Coraval library to schedule the tasks.
Program.cs
class
public class Program
{
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.File(@"C:\temp\Workerservice\logfile.txt").CreateLogger();
IHost host = CreateHostBuilder(args).Build();
host.Services.UseScheduler(scheduler =>
{
scheduler
.Schedule()
.EveryThirtySeconds();
});
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).UseSystemd() //.UseWindowsService()
.ConfigureServices(services =>
{
services.AddScheduler();
services.AddTransient();
});
}
ReprocessInvocable.cs
class
public class ReprocessInvocable : IInvocable
{
private readonly ILogger _logger;
public ReprocessInvocable(ILogger logger)
{
_logger = logger;
}
public async Task Invoke()
{
//your code goes here
_logger.LogInformation("Information - Worker running at: {time}", DateTimeOffset.Now);
_logger.LogWarning("Warning - Worker running at: {time}", DateTimeOffset.Now);
_logger.LogCritical("Critical - Worker running at: {time}", DateTimeOffset.Now);
Log.Information("Invoke has called at: {time}", DateTimeOffset.Now);
}
}
For linux daemon
use UseSystemd
and for windows service
use UseWindowsService
as per the above code.