Does your company or startup need an expert? If so, write to me to talk about possibilities of professional cooperation.
PROGRAMMING on-line course is approaching! Write to me if you are interested in free early access.

MARCIN.com

Marcin Jamro, PhD, DSc

How to implement background service executing actions every hour?

C#  |  .NET  |  ASP.NET

There is often the necessity to perform some tasks periodically in the background, such as every hour or every 6 hours. Fortunately, you can easily create such a mechanism in your ASP.NET Core web application with a background service.

First, let's define a class representing the background service. Within it, you can specify frequency of actions, as well as write the code that will be executed cyclically, as presented below:

public class HourlyBackgroundService(IServiceProvider serviceProvider)
    : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using PeriodicTimer timer = new(TimeSpan.FromHours(1));
        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            using IServiceScope scope = serviceProvider.CreateScope();
            using AppDbContext dbContext = 
                scope.ServiceProvider.GetRequiredService();
            /* Database-related operations */
            Console.WriteLine($"{DateTime.Now:HH:mm:ss}");
        }
    }
}

To start background service execution, you need to configure it in the Program.cs file, as follows:

WebApplicationBuilder builder = WebApplication.CreateBuilder(args); (...)
builder.Services.AddHostedService(); (...)
WebApplication app = builder.Build(); (...)

The content, including any part of code, is presented without warranty, either express or implied. The author cannot be held liable for any damages caused or alleged to have been caused directly or indirectly by any content shown on this website.

Hello, I am Marcin

Reliable entrepreneur with 10+ years of companies operation, such as CEO at a few IT companies. I was an author of a few software & hardware products, still open to new ideas & cooperation.

Helpful expert with 10+ years of experience, together with PhD and DSc in Computer Science. I was an author of books and publications, as well as an expert in international projects.

Experienced developer with 10+ years of development and 100+ completed projects. I worked on various complex international projects, e.g. at Microsoft in USA and as CTO at a few companies. I have MCP, MCTS and MCPD certificates.

You can read more about me in my short bio. I am waiting for contact at [email protected], as well as at my Facebook and LinkedIn profiles.

Books

I am an author of a few books and numerous publications, also in high-quality international scientific journals.

If you want to learn data structures and algorithms in the context of C#, let's take a look at my newest book. It is the second edition of C# Data Structures and Algorithms. You can buy it here.

Projects

Do you like traveling? If so, discover an amazing world with local guides, right here and right now at: https://camaica.com

Do you follow your favorite creators? If so, check it out what products they recommend and buy them at: https://refspace.com

Travels

I love travels, learning new cultures and regions, meeting outstanding people, as well as taking pictures of beautiful places. Take a look at my travel diary.