Automatically call a function after certain time period in .Net?

Waqas
2 min readJul 20, 2023

--

In .NET, you can call a function after a certain time period automatically using various approaches. Here are two common methods:

  1. Using System.Threading.Timer:
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
// Set the time interval for the function to be called (e.g., every 5 seconds)
int intervalMilliseconds = 5000;
// Create a Timer that calls the function automatically after the specified interval
Timer timer = new Timer(ExecuteFunction, null, 0, intervalMilliseconds);
// Keep the program running to allow the Timer to continue calling the function
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
// Dispose of the timer when you're done with it (e.g., when the program is exiting)
timer.Dispose();
}
static void ExecuteFunction(object state)
{
// Put the code of the function you want to call here
Console.WriteLine("Function called at: " + DateTime.Now);
}
}
  1. Using System.Threading.Tasks.Task.Delay:
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// Set the time interval for the function to be called (e.g., every 5 seconds)
int intervalMilliseconds = 5000;
// Infinite loop to call the function with the specified interval
while (true)
{
ExecuteFunction();
// Delay the next execution of the function
await Task.Delay(intervalMilliseconds);
}
}
static void ExecuteFunction()
{
// Put the code of the function you want to call here
Console.WriteLine("Function called at: " + DateTime.Now);
}
}

Both approaches will call the ExecuteFunction at the specified time interval. The first example using System.Threading.Timer is more suitable when you have multiple timers and need more control over timer behavior, while the second example using System.Threading.Tasks.Task.Delay is a more straightforward approach. Choose the one that fits your requirements best.

--

--