Skip to content

Commit

Permalink
Add hosted service example
Browse files Browse the repository at this point in the history
  • Loading branch information
jmeline committed Jan 21, 2025
1 parent 8888b25 commit de04b1c
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 0 deletions.
13 changes: 13 additions & 0 deletions HostedService/HostedService.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>dotnet-HostedService-ce7be10a-35b0-475e-a813-dfa2f8e9436e</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.0" />
</ItemGroup>
</Project>
7 changes: 7 additions & 0 deletions HostedService/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
using HostedService;

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<Worker>();

var host = builder.Build();
host.Run();
12 changes: 12 additions & 0 deletions HostedService/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"HostedService": {
"commandName": "Project",
"dotnetRunMessages": true,
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}
16 changes: 16 additions & 0 deletions HostedService/Worker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace HostedService;

public class Worker(ILogger<Worker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
}
await Task.Delay(1000, stoppingToken);
}
}
}
8 changes: 8 additions & 0 deletions HostedService/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
8 changes: 8 additions & 0 deletions HostedService/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

0 comments on commit de04b1c

Please sign in to comment.