Create and register window service

 Visual Studio:

  • Create New Project

  • Select Worker Service

  • Target .NET 6/7/8


  • Modify Program.cs file:
    using Microsoft.Extensions.Hosting;

    Host.CreateDefaultBuilder(args)
    .UseWindowsService() // Important
    .ConfigureServices((hostContext, services) =>
    {
    services.AddHostedService<Worker>();
    })
    .Build()
    .Run();
  • using Microsoft.Extensions.DependencyInjection;
Implement Database Update Logic
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Data.SqlClient;
using System;
using System.Threading;
using System.Threading.Tasks;

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly string _connectionString =
        "Server=YOUR_SERVER;Database=YOUR_DB;Trusted_Connection=True;";

    public Worker(ILogger<Worker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Service Started");

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await UpdateDatabase();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating database");
            }

            await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); // Run every 5 min
        }
    }

    private async Task UpdateDatabase()
    {
        using var connection = new SqlConnection(_connectionString);
        await connection.OpenAsync();

        using var command = new SqlCommand(
            "UPDATE YourTable SET Status = 1 WHERE Status = 0",
            connection);

        var rows = await command.ExecuteNonQueryAsync();
        _logger.LogInformation($"Updated {rows} rows");
    }
}
Publish the Service:
bin\Release\net8.0\win-x64\publish\

Register the Windows Service:(Use power shell)
New-Service -Name "DatabaseUpdateService" `
  -BinaryPathName "C:\Path\To\publish\DatabaseUpdateService.exe" `
  -DisplayName "Database Update Service" `
  -StartupType Automatic

Comments

Popular posts from this blog

Key points while writting prompt for AI

How Create API in python using flask library

Book teams appointment with email notification