Execute specified function every X seconds

Use System.Windows.Forms.Timer.

private Timer timer1; 
public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 2000; // in miliseconds
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    isonline();
}

You can call InitTimer() in Form1_Load().


The most beginner-friendly solution is:

Drag a Timer from the Toolbox, give it a Name, set your desired Interval, and set "Enabled" to True. Then double-click the Timer and Visual Studio (or whatever you are using) will write the following code for you:

private void wait_Tick(object sender, EventArgs e)
{
    refreshText(); // Add the method you want to call here.
}

No need to worry about pasting it into the wrong code block or something like that.


.NET 6 has added the PeriodicTimer class.

var periodicTimer= new PeriodicTimer(TimeSpan.FromSeconds(1));
while (await periodicTimer.WaitForNextTickAsync())
{
    // Place function in here..
    Console.WriteLine("Printing");
}

You can run it in the background with this:

async Task RunInBackground(TimeSpan timeSpan, Action action)
{
    var periodicTimer = new PeriodicTimer(timeSpan);
    while (await periodicTimer.WaitForNextTickAsync())
    {
        action();
    }
}

RunInBackground(TimeSpan.FromSeconds(1), () => Console.WriteLine("Printing"));

The main advantage PeriodicTimer has over a Timer.Delay loop is best observed when executing a slow task.

using System.Diagnostics;

var stopwatch = Stopwatch.StartNew();
// Uncomment to run this section
//while (true)
//{
//    await Task.Delay(1000);
//    Console.WriteLine($"Delay Time: {stopwatch.ElapsedMilliseconds}");
//    await SomeLongTask();
//}

//Delay Time: 1007
//Delay Time: 2535
//Delay Time: 4062
//Delay Time: 5584
//Delay Time: 7104

var periodicTimer = new PeriodicTimer(TimeSpan.FromMilliseconds(1000));
while (await periodicTimer.WaitForNextTickAsync())
{
    Console.WriteLine($"Periodic Time: {stopwatch.ElapsedMilliseconds}");
    await SomeLongTask();
}

//Periodic Time: 1016
//Periodic Time: 2027
//Periodic Time: 3002
//Periodic Time: 4009
//Periodic Time: 5018

async Task SomeLongTask()
{
    await Task.Delay(500);
}

PeriodicTimer will attempt to invoke every n * delay seconds, whereas Timer.Delay will invoke every n * (delay + time for method to run) seconds, causing execution time to gradually move out of sync.

Tags:

C#

.Net

Winforms