Code Examples

Call a function with time interval

programming

The following code examples will show you how to call a function repeatedly after a certain time period.

Code in C#

private static System.Timers.Timer aTimer;
private static int counter = 0;

public static void Main()
{
    SetTimer();
}



public static void SetTimer()
{
    // Create a timer with a two second interval.
    aTimer = new System.Timers.Timer(2000);
    // Hook up the Elapsed event for the timer. 
    aTimer.Elapsed += OnTimedEvent;
    aTimer.Start();

}


private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    // we will run the event 10 times
    if (counter < 10)
    {
        Console.WriteLine("Procedure call: " + counter);
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                      e.SignalTime);
        counter++;
    }
    else
    {
        aTimer.Stop();
        aTimer.Dispose();
        counter = 0;
        Console.WriteLine("Timer stopped.");
    }
}

Code in Python

import time

# this code will print the message
# every 10 seconds while condition remains True
def setTimer():
    while True:
        print("tick")
        # will sleep 10 seconds after each call
        time.sleep(10)        
        
setTimer()