Click here to Skip to main content
15,884,872 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I want to use timer in windows forms.I should be such that I have 4 functions to be called with 5 sec difference.5secs after function1() execution it should execute function2() etc.I am working with C#.How can I do this?Any help appreciated.

What I have tried:

I have tried for single function call in timer.
Posted
Updated 23-Apr-18 3:16am
Comments
George Swan 23-Apr-18 1:34am    
Do your methods return void?
Member 13688117 23-Apr-18 2:01am    
yes

Create a class level integer variable call callNext.
Then in your Timer Tick event:
C#
switch(callNext++)
   {
   case 0: Method0(); break;
   case 1: Method1(); break;
   case 2: Method2(); break;
   case 3: Method3(); break;
   }
if (callNext > 3) callNext = 0;
TO make it clearer, you could use an enum instead of an integer.
 
Share this answer
 
v2
Comments
Member 13688117 23-Apr-18 2:17am    
Thank you.Its working.
OriginalGriff 23-Apr-18 2:26am    
You're welcome!

If you need to make sure that there is a five second delay after each method finishes rather than just running the methods sequentially, with a method being called every 5 seconds, you can use the task based asynchronous pattern. In this example the functions are called in response to a button click. The functions will run on the UI thread but the 5 second delay will be an asynchronous delay and will not block the UI thread.


C#
private async void BtnRun_Click(object sender, EventArgs e)
        {
             function1();
            await Task.Delay(5000);
            function2();
            await Task.Delay(5000);
            function3();
            await Task.Delay(5000);
            function4();
        }

If the functions are all Actions you can refactor the method by using a List<Action>

 
Share this answer
 
Comments
Member 13688117 24-Apr-18 0:06am    
Thank you so much very apt answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900