Search code examples
c#timersystem.timers.timer

C# Timer firing too early


When I call the Method random_Start() it works at first: The second console print comes at a reasonable time, but then the gap between the console prints gets smaller and smaller.

After some prints, almost every print comes after way less than 5 Seconds, although the code should set a Timer for at least 5 Seconds, right?


        static Timer timer;
        static Random random = new Random();
        public static void random_Start()
        {
            timer = new Timer(random.NextDouble()*10000+5000);
            timer.Elapsed += OnTimedEvent;
            timer.Start();
            Console.WriteLine("Start");
        }

        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            random_Start();
        }

Solution

  • Setup your timer so that you aren't creating a new instance with every timer tick. In the example below, I've disabled AutoReset so that we can set a new interval and start the timer again manually.

        static Timer timer;
        static Random random = new Random();
        public static void random_Start()
        {
            timer = new Timer(random.NextDouble()*10000+5000);
            timer.Elapsed += OnTimedEvent;
            timer.AutoReset = false;
            timer.Start();
            Console.WriteLine("Start");
        }
    
        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            Console.WriteLine("Tick");
            timer.Interval = random.NextDouble()*10000+5000;
            timer.Start();
        }