Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a function every 2 seconds

Tags:

function

c#

timer

    public void InitTimer()
    {
        timer1 = new Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 200; // in milliseconds
        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("test");
    }

Using that code from How can I raise an event every hour (or specific time interval each hour) in .NET?

I'm VERY new to C#, but I'm not sure what's wrong. I'm trying to display a messagebox in this example every 2 seconds. There are no errors, the messagebox simply does not show.

like image 216
Prash Avatar asked Mar 26 '26 23:03

Prash


2 Answers

You forgot to call the function in your load.

like image 162
Skami Avatar answered Mar 29 '26 13:03

Skami


I tried out your code (changing 200ms to 2000ms), and it did display the message box every 2 seconds, so the problem is not the code, but more likely the way you are calling it. I just created a sample Winforms app, and put the call to InitTimer in the form's Load event:

    private void Form1_Load(object sender, EventArgs e)
    {
        InitTimer();
    }

When you created the project, did you create a Windows Forms application? You should not have created a Console application, for example.

like image 21
JohnD Avatar answered Mar 29 '26 13:03

JohnD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!