Home >Backend Development >C++ >How Can I Schedule a Method to Run Every X Minutes in C#?

How Can I Schedule a Method to Run Every X Minutes in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-06 14:50:411007browse

How Can I Schedule a Method to Run Every X Minutes in C#?

Scheduled Method Invocation Every X Minutes

To schedule a method to run periodically, you can harness the power of a timer. Let's delve into how this can be achieved in C#:

Utilizing a System Timer

Consider the following code to instantiate a System.Threading.Timer:

var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);

var timer = new System.Threading.Timer((e) =>
{
    MyMethod();   
}, null, startTimeSpan, periodTimeSpan);

This technique employs a timer that commences execution immediately (startTimeSpan is set to TimeSpan.Zero) and subsequently invokes MyMethod() every 5 minutes (periodTimeSpan is set to 5 minutes).

Note: An updated and recommended approach to scheduling tasks in .NET Core can be found here: https://stackoverflow.com/a/70887955/426894

By harnessing this powerful tool, you can conveniently schedule tasks to execute periodically at defined intervals, enhancing the maintainability and precision of your applications.

The above is the detailed content of How Can I Schedule a Method to Run Every X Minutes in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn