Skip to content

Instantly share code, notes, and snippets.

@glennc
Last active August 20, 2019 04:54
Show Gist options
  • Save glennc/9f16cb8f29916d5be7e89287cb18e5a0 to your computer and use it in GitHub Desktop.
Save glennc/9f16cb8f29916d5be7e89287cb18e5a0 to your computer and use it in GitHub Desktop.
Code for systemd post
Jul 30 01:05:14 glennc-systemd testapp[44516]: Microsoft.Hosting.Lifetime[0] Application started. Hosting environment: Production; Content root path: /
Jul 30 01:05:15 glennc-systemd testapp[44516]: testapp.Worker[0] Worker running at: 07/30/2019 01:05:15 +00:00
Jul 30 01:05:16 glennc-systemd testapp[44516]: testapp.Worker[0] Worker running at: 07/30/2019 01:05:16 +00:00
Jul 30 01:05:17 glennc-systemd testapp[44516]: testapp.Worker[0] Worker running at: 07/30/2019 01:05:17 +00:00
Jul 30 01:05:18 glennc-systemd testapp[44516]: testapp.Worker[0] Worker running at: 07/30/2019 01:05:18 +00:00
Jul 30 01:05:19 glennc-systemd testapp[44516]: testapp.Worker[0] Worker running at: 07/30/2019 01:05:19 +00:00
Jul 30 01:05:20 glennc-systemd testapp[44516]: testapp.Worker[0] Worker running at: 07/30/2019 01:05:20 +00:00
Jul 30 01:05:21 glennc-systemd testapp[44516]: testapp.Worker[0] Worker running at: 07/30/2019 01:05:21 +00:00
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSystemd()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<UserSecretsId>dotnet-testapp-F2B98682-0CD2-4F05-967B-716D6E4CA95C</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0-preview7.19362.4" />
<PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="3.0.0-preview7.19362.4" />
</ItemGroup>
</Project>
[Unit]
Description=my test app
[Service]
Type=notify
ExecStart=/usr/sbin/testapp
[Install]
WantedBy=multi-user.target
public Worker(ILogger<Worker> logger, IHostLifetime lifetime)
{
_logger = logger;
_logger.LogInformation("IsSystemd: {isSystemd}", lifetime.GetType() == typeof(SystemdLifetime));
_logger.LogInformation("IHostLifetime: {hostLifetime}", lifetime.GetType());
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogCritical("Critical log on startup.");
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment