[c#] 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();
    }
}

This question is related to c#

The answer is


while (true)
{
    Thread.Sleep(60 * 5 * 1000);
    Console.WriteLine("*** calling MyMethod *** ");
    MyMethod();
}

I've uploaded a Nuget Package that can make it so simple, you can have it from here ActionScheduler

It supports .NET Standard 2.0

And here how to start using it

using ActionScheduler;

var jobScheduler = new JobScheduler(TimeSpan.FromMinutes(8), new Action(() => {
  //What you want to execute
}));

jobScheduler.Start(); // To Start up the Scheduler

jobScheduler.Stop(); // To Stop Scheduler from Running.

Example of using a Timer:

using System;
using System.Timers;

static void Main(string[] args)
{
    Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // Set the time (5 mins in this case)
    t.AutoReset = true;
    t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
    t.Start();
}

// This method is called every 5 mins
private static void your_method(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("..."); 
}

Using a DispatcherTimer:

 var _activeTimer = new DispatcherTimer {
   Interval = TimeSpan.FromMinutes(5)
 };
 _activeTimer.Tick += delegate (object sender, EventArgs e) { 
   YourMethod(); 
 };
 _activeTimer.Start();          

Use a Timer. Timer documentation.


Start a timer in the constructor of your class. The interval is in milliseconds so 5*60 seconds = 300 seconds = 300000 milliseconds.

static void Main(string[] args)
{
    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Interval = 300000;
    timer.Elapsed += timer_Elapsed;
    timer.Start();
}

Then call GetData() in the timer_Elapsed event like this:

static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    //YourCode
}

I based this on @asawyer's answer. He doesn't seem to get a compile error, but some of us do. Here is a version which the C# compiler in Visual Studio 2010 will accept.

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