JS's setInterval and setTimeOut is really convenient. And I want to ask how to implement the same thing in C#.
The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. You can cancel the interval using clearInterval() .
The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)
What is the use of setInterval() method in Node. js ? The setInterval() method helps us to repeatedly execute a function after a fixed delay. It returns a unique interval ID which can later be used by the clearInterval() method which stops further repeated execution of the function.
You can just do a Task.Delay
within a Task.Run
, try out:
var task = Task.Run(async () => {
for(;;)
{
await Task.Delay(10000)
Console.WriteLine("Hello World after 10 seconds")
}
});
Then You could even wrap this up in to your own SetInterval method that takes in an action
class Program
{
static void Main(string[] args)
{
SetInterval(() => Console.WriteLine("Hello World"), TimeSpan.FromSeconds(2));
SetInterval(() => Console.WriteLine("Hello Stackoverflow"), TimeSpan.FromSeconds(4));
Thread.Sleep(TimeSpan.FromMinutes(1));
}
public static async Task SetInterval(Action action, TimeSpan timeout)
{
await Task.Delay(timeout).ConfigureAwait(false);
action();
SetInterval(action, timeout);
}
}
or you could just use the built in Timer class which practically does the same thing
static void Main(string[] args)
{
var timer1 = new Timer(_ => Console.WriteLine("Hello World"), null, 0, 2000);
var timer2 = new Timer(_ => Console.WriteLine("Hello Stackoverflow"), null, 0, 4000);
Thread.Sleep(TimeSpan.FromMinutes(1));
}
Just make sure you're timers don't go out of scope and get disposed.
.NET 6 Update
.NET 6 introduced a new type called PeriodicTimer
this simplifies the above, and can be used like the following:
var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
while (await timer.WaitForNextTickAsync())
{
Console.WriteLine("Hello World after 10 seconds")
}
If you need to be able to cancel the timer the WaitForNextTickAsync
function has an overload for
a cancellation token.
Its simply like this, you define an static System.Timers.Timer; then call the function that binds the timer.Elapsed event to your interval function that will be called each X miliseconds.
public class StaticCache {
private static System.Timers.Timer syncTimer;
StaticCache(){
SetSyncTimer();
}
private void SetSyncTimer(){
// Create a timer with a five second interval.
syncTimer = new System.Timers.Timer(5000);
// Hook up the Elapsed event for the timer.
syncTimer.Elapsed += SynchronizeCache;
syncTimer.AutoReset = true;
syncTimer.Enabled = true;
}
private static void SynchronizeCache(Object source, ElapsedEventArgs e)
{
// do this stuff each 5 seconds
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With