JS\'s setInterval and setTimeOut is really convenient. And I want to ask how to implement the same thing in C#.
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.
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
}
}