Search code examples
c#timer

Timer not executing which defined under UtilityClass constructor


I would like to execute a C# method every 10 sec and I am using in a UtilityClass class constructor, but method is not executing and I'm not getting any output.

class Program
{
    static void Main(string[] args)
    {
        UtilityClass utilityClass = new UtilityClass();
    }
}

public class UtilityClass : IDisposable
{
    private readonly System.Timers.Timer _Timer;

    public UtilityClass()
    {
        _Timer = new System.Timers.Timer(TimeSpan.FromSeconds(10).TotalMilliseconds);
        _Timer.Elapsed += (sender, eventArgs) =>
        {
            ExecuteEvery10Sec();
        };
    }

    private void ExecuteEvery10Sec()
    {
        Console.WriteLine($"Every 10 sec all at {DateTime.Now}");
    }

    public void Dispose()
    {
        _Timer.Dispose();
    }
}

Solution

  • There are two problems: one - the program immediately terminated, so the timer is destroyed. You should wait to something. For example, waiting 10 minutes:

    class Program
    {
        static void Main(string[] args)
        {
            using (UtilityClass utilityClass = new UtilityClass()) // To dispose after the use
            {
                System.Threading.Thread.Sleep(10000 * 60); // Waits X milliseconds
            }
        }
    }
    

    Edit:

    You also can to execute an infinite loop, so the ser exit onlyy by the X button of the console (or by Ctrl+C). So:

    class Program
    {
        static void Main(string[] args)
        {
            using (UtilityClass utilityClass = new UtilityClass()) // To dispose after the use
            {
                while (true) { }
            }
        }
    }
    

    two - You should start the timer, by setting its Enabled property to true:

    public class UtilityClass : IDisposable
    {
        private readonly System.Timers.Timer _Timer;
    
        public UtilityClass()
        {
            _Timer = new System.Timers.Timer(TimeSpan.FromSeconds(10).TotalMilliseconds);
            _Timer.Enabled = true;
            _Timer.Elapsed += (sender, eventArgs) =>
            {
                ExecuteEvery10Sec();
            };
        }
    
        private void ExecuteEvery10Sec()
        {
            Console.WriteLine($"Every 10 sec all at {DateTime.Now}");
        }
    
        public void Dispose()
        {
            _Timer.Dispose();
        }
    }