Search code examples
c#timerperiodictimer

Calling a method every x minutes


I want to call some method on every 5 minutes. How can I do this?

public class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("*** calling MyMethod *** ");
        Console.ReadLine();
    }

    private MyMethod()
    {
        Console.WriteLine("*** Method is executed at {0} ***", DateTime.Now);
        Console.ReadLine();
    }
}

Solution

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

    Edit - this answer is out of date. See https://stackoverflow.com/a/70887955/426894