johniek_comp
johniek_comp

Reputation: 322

Timer in C# that fires X seconds after opening program?

How can I run a function, after 10 seconds, after the opening of the program.

This is what I tried, and I'm not able to make it work.

private void button1_Click(object sender, EventArgs e)
{
    Timer tm = new Timer();
    tm.Enabled = true;
    tm.Interval = 60000;
    tm.Tick+=new EventHandler(tm_Tick);
}
private void tm_Tick(object sender, EventArgs e)
{
    Form2 frm = new Form2();
    frm.Show();
    this.Hide();
}

Upvotes: 3

Views: 6895

Answers (2)

David Heffernan
David Heffernan

Reputation: 612794

You have a few problems:

  1. You need to use the Load event rather than a button click handler.
  2. You should set the interval to 10000 for a 10 second wait.
  3. You are using a local variable for the timer instance. That makes it hard for you to refer to the timer at a later date. Make the timer instance be a member of the form class instead.
  4. Remember to stop the clock after you run the form, or, it will try to open every 10 seconds

In other words, something like this:

private Timer tm;

private void Form1_Load(object sender, EventArgs e)
{
    tm = new Timer();
    tm.Interval = 10 * 1000; // 10 seconds
    tm.Tick += new EventHandler(tm_Tick);
    tm.Start();
}

private void tm_Tick(object sender, EventArgs e)
{
    tm.Stop(); // so that we only fire the timer message once

    Form2 frm = new Form2();
    frm.Show();
    this.Hide();
}

Upvotes: 14

Smit
Smit

Reputation: 609

Is will be good for your program something like that?

namespace Timer10Sec
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(new ThreadStart(After10Sec));
            t.Start();
        }

        public static void After10Sec()
        {
            Thread.Sleep(10000);
            while (true)
            {
                Console.WriteLine("qwerty");
            }
        }
    }
}

Upvotes: 0

Related Questions