Search code examples
c#asp.net-coreasp.net-web-apihangfirerecurring-events

How can I schedule a recurring task to run at specific intervals in C#?


I would like to set up a task to execute at regular intervals, such as every hour, in C#. How can I accomplish this?

Update:

Thank you for the assistance. After conducting some research, I discovered that I can achieve recurring jobs by utilizing Hangfire. This approach eliminates the need for a Windows Service or a separate process and is remarkably straightforward to implement. If anyone is encountering a similar issue, I recommend giving it a try.

Hangfire Documentation: https://www.hangfire.io/


Solution

  • You can implement a background task that runs as a hosted service, see the following example at Microsoft

    Summary:

    • Add your background task where you configure your services (dependency injection), e.g. services.AddHostedService<MyDataFetcher>();
    • Implement the MyDataFetcher class, and make it inherit from IHostedService and IDisposable, e.g.: public class MyDataFetcher : IHostedService, IDisposable
    • Ensure your service is always on (and not put to sleep when not in use)