Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a method after a specific time interval?

Tags:

It's clear: For example, imagine a button in my form. When a user clicks on the button, some void method should run after 30 seconds.

There would be a void method DoAfterDelay that takes two input parameter. The first one is the method to do (using delegates), and the other one is the time interval. So I'll have:

public delegate void IVoidDelegate(); static void DoAfterDelay(IVoidDelegate TheMethod, TimeSpan Interval)     {         // *** Some code that will pause the process for "Interval".         TheMethod();     } 

So, I just need a piece of code to pause the process for a specific time interval. Heretofore, I used this code to do that:

System.Threading.Thread.Sleep(Interval); 

But this code is no good for me, because it stops the whole process and freezes the program. I don't want the program to get stuck in the DoAfterDelay method. That's why the Thread.Sleep is useless.

So could anyone suggest a better way? Of course I've searched about that, but most of the solutions I've found were based on using a timer (like here for example). But using a timer is my last opinion, because the method should run once and using timers makes the program confusing to read. So I'm looking for a better solution if there is. Or maybe I have to use timers?

I guess I have to play with threads, but not sure. So I wonder if anyone could guide me to a solution. Thanks in advance.

like image 682
Mostafa Farzán Avatar asked Jun 23 '14 17:06

Mostafa Farzán


People also ask

How do you call a function after a specific time?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.

Which can be used to execute a function over and over again at specific time intervals?

You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.


2 Answers

Can you use a task?

Task.Factory.StartNew(() => {     System.Threading.Thread.Sleep(Interval);     TheMethod(); });  
like image 178
Bartosz Wójtowicz Avatar answered Oct 25 '22 10:10

Bartosz Wójtowicz


This is where you can use the async await functionality of .Net 4.5

You can use Task.Delay an give the delay in miliseconds. This is a very clean way. ex:

private async void button1_Click(object sender, EventArgs e) {     await Task.Delay(5000);      TheMethod(); } 
like image 27
Jimmy Hannon Avatar answered Oct 25 '22 09:10

Jimmy Hannon