none
Timer not stopping RRS feed

  • Question

  • Hi Experts, 

    The below code works fine which I got from a previously asked thread but now the issue is .

    1. If I remove the Console.Readkey() it executes only for 5 times ..
    2. If I don't remove the Console.ReadKey() it executes forever and unable to stop using Ctrl + C.

    Could you please help with its optimization, that it stops on Ctrl +  C and also doesn't run forever.

    I require the timer in windows service.

     static void Main(string[] args)
            {
                int interval = int.Parse(ConfigurationManager.AppSettings["interval"]);
                System.Threading.Timer timer = new System.Threading.Timer(Start,null,1,interval);
    
                Console.ReadKey();
            }
    
            private static void Start(object state)
            {
                Console.WriteLine("Do something here.");
            }

    Thanks 

    Priya


    • Edited by Priya Bange Tuesday, December 3, 2019 5:23 AM ..
    Tuesday, December 3, 2019 5:03 AM

All replies

  • Quick example for that with your current code could be something like:

    class Program
    {
        class TimerState
        {
            public int MaxExecutionCount { get; set; }
    
            public int ExecutionCount { get; set; }
    
            public bool Exit { get; set; }
        }
    
        static void Main(string[] args)
        {
            int interval = 500;
                
            TimerState state = new TimerState() { MaxExecutionCount = 5, ExecutionCount = 0, Exit = false };
    
            System.Threading.Timer timer = new System.Threading.Timer(Start, state, 1, interval);
            ConsoleKeyInfo keyInfo;
    
            while (!state.Exit)
            {
                do
                {
                    keyInfo = Console.ReadKey();
                }
                while (!(keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.C));
            }
    
    
            timer.Dispose();
        }
    
        private static void Start(object state)
        {
            TimerState timerState = (TimerState)state;
    
            if (timerState.ExecutionCount >= timerState.MaxExecutionCount)
            {
                timerState.Exit = true;
                return;
            }
    
            timerState.ExecutionCount += 1;
    
            Console.WriteLine("Do something here.");
        }
    }

    Tuesday, December 3, 2019 5:39 AM
  • Quick example for that with your current code could be something like:

    class Program
    {
        class TimerState
        {
            public int MaxExecutionCount { get; set; }
    
            public int ExecutionCount { get; set; }
    
            public bool Exit { get; set; }
        }
    
        static void Main(string[] args)
        {
            int interval = 500;
                
            TimerState state = new TimerState() { MaxExecutionCount = 5, ExecutionCount = 0, Exit = false };
    
            System.Threading.Timer timer = new System.Threading.Timer(Start, state, 1, interval);
            ConsoleKeyInfo keyInfo;
    
            while (!state.Exit)
            {
                do
                {
                    keyInfo = Console.ReadKey();
                }
                while (!(keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.C));
            }
    
    
            timer.Dispose();
        }
    
        private static void Start(object state)
        {
            TimerState timerState = (TimerState)state;
    
            if (timerState.ExecutionCount >= timerState.MaxExecutionCount)
            {
                timerState.Exit = true;
                return;
            }
    
            timerState.ExecutionCount += 1;
    
            Console.WriteLine("Do something here.");
        }
    }

    Dear Sir,

    I wish it to continuously run in my windows service & every 15-20 seconds depending on my interval parameter execute the method. I see a check of 5 in the above for execution count. Please suggest if any changes need to be performed to make it run endlessly without much overhead. 

    Thanks again

    Tuesday, December 3, 2019 6:50 AM
  • Yes, the above is for your previous requirements of "If I remove the Console.Readkey() it executes only for 5 times ..".

    For Window service you can remove any key or execution count check and just let Timer execute as long as the service is on. So you start timer at when service start and dispose it when service stop.

    What comes to overhead, that mainly depends what you are doing in method executed every 15-20 seconds?

    Tuesday, December 3, 2019 7:04 AM
  • Yes, the above is for your previous requirements of "If I remove the Console.Readkey() it executes only for 5 times ..".

    For Window service you can remove any key or execution count check and just let Timer execute as long as the service is on. So you start timer at when service start and dispose it when service stop.

    What comes to overhead, that mainly depends what you are doing in method executed every 15-20 seconds?

    Dear Sir,

    My service is basically querying a SQL Server DB every 15 second's read a table and exits... Am actually a SQL Developer and C# is new for me. So, could you please help how I can remove the check of 5 seconds and just keep interval parameter of 15 second's for calling my method.. Am using topshelf for my windows service.

    Tuesday, December 3, 2019 7:09 AM
  • Hi Sir,

    I used this at it works fine on Command Line.. 

    https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.8

    but when I have installed it as a windows service. The timer isn't executing ..


    • Edited by Priya Bange Tuesday, December 3, 2019 8:02 AM .
    Tuesday, December 3, 2019 7:52 AM
  • Am trying the below code, it works absolutely on console but when I try to convert it to a service. It stops working. 

    class Request
        {
            int interval = int.Parse(ConfigurationManager.AppSettings["Interval"]); // 15000
    
            private static System.Timers.Timer aTimer;
    
            public bool Start()
            {
                 SetTimer();
                
           
                return true;
            }
    
            private void SetTimer()
            {
                aTimer = new System.Timers.Timer(interval);
                aTimer.Elapsed += PrintBelow;
                aTimer.AutoReset = true;
                aTimer.Enabled = true;
            }
    
    
            public bool Stop()
            {
                aTimer.Stop();
                aTimer.Dispose();
                return true;
            }
    
            public void PrintBelow(object sender, ElapsedEventArgs e)
            {
                Console.WriteLine("Executed again");
    
         }
    	 
    	 }

    Tuesday, December 3, 2019 8:18 AM
  • Hello,

    Could anyone please share the reason, why the timer is not getting activated when the console is converted to Windows service. 

    Thanks 

    Priya

    Wednesday, December 4, 2019 6:25 AM
  • Hi Priya Bange,
    The System.Timers.Timer component is a server-based timer.
    The System.Threading.Timer executes a single callback method on a thread pool thread at regular intervals.
    You can try to use the System.Threading.Timer.
    More details you can refer to the Adam Houldsworth's answer.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, December 4, 2019 7:13 AM