Calling a method every x minutes

C#

C# Problem Overview


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();
    }
}

C# Solutions


Solution 1 - C#

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

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

Solution 2 - C#

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));

Solution 3 - C#

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
}

Solution 4 - C#

Update .NET 6

For most use cases in dotnet 6+, you should use the PeriodicTimer:

var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));

while (await timer.WaitForNextTickAsync())
{
    //Business logic
}

This has several advantages, including async / await support, avoiding memory leaks from callbacks, and CancelationToken support

Further Reading

Solution 5 - C#

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("..."); 
}

Solution 6 - C#

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.

Solution 7 - C#

Use a Timer. Timer documentation.

Solution 8 - C#

Using a DispatcherTimer:

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

Solution 9 - C#

If you need more complicated time executions such as linux cron, you can use NCrontab.

I use NCrontab in production for long time and it works perfect!

Nuget

How to use:

* * * * *
- - - - -
| | | | |
| | | | +----- day of week (0 - 6) (Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)
using NCrontab;
//...

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
  // run every 5 minutes
  var schedule = CrontabSchedule.Parse("*/5 * * * *");
  var nextRun = schedule.GetNextOccurrence(DateTime.Now);
  logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);    
  do
  {
    if (DateTime.Now > nextRun)
    {
      logger.LogInformation("Sending notifications at: {time}", DateTimeOffset.Now);
      await DoSomethingAsync();
      nextRun = schedule.GetNextOccurrence(DateTime.Now);
    }
    await Task.Delay(1000, stoppingToken);
  } while (!stoppingToken.IsCancellationRequested);
}

Add seconds if you need:

// run every 10 secs
var schedule = CrontabSchedule.Parse("0/10 * * * * *", new CrontabSchedule.ParseOptions { IncludingSeconds = true });

Solution 10 - C#

It can be achieved by applying while loop and calling Thread.Sleep at the end of the loop.

while (true)
{
    //Your code
    Thread.Sleep(5000);
}

Make sure to include using System.Threading.

Solution 11 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1765862View Question on Stackoverflow
Solution 1 - C#asawyerView Answer on Stackoverflow
Solution 2 - C#André C. AndersenView Answer on Stackoverflow
Solution 3 - C#Maiko KingmaView Answer on Stackoverflow
Solution 4 - C#KyleMitView Answer on Stackoverflow
Solution 5 - C#PJ3View Answer on Stackoverflow
Solution 6 - C#Ahmed AbuelnourView Answer on Stackoverflow
Solution 7 - C#Chuck ConwayView Answer on Stackoverflow
Solution 8 - C#BloggrammerView Answer on Stackoverflow
Solution 9 - C#PatoView Answer on Stackoverflow
Solution 10 - C#Mansour FahadView Answer on Stackoverflow
Solution 11 - C#Dennis TraubView Answer on Stackoverflow