A timer in C # that starts X seconds after opening a program?

How to start a function 10 seconds after opening a program.

This is what I tried, and I cannot get it to 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();
}
+3
source share
2 answers

You have a few problems:

  • You need to use an event Load, not a button click handler.
  • You must set the interval 10000to 10 seconds to wait.
  • You are using a local variable for the timer instance. This makes it difficult for you to access the timer later. Make a timer instance instead of a form member.
  • Remember to stop the clock after running the form or 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();
}
+13
source

- ?

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");
            }
        }
    }
}
0

All Articles