none
the timer not working correctly RRS feed

  • Question

  • hi ;

    I have a structure like below in Service1.cs ,I just have a little problem.

    thus ; I just want to execute code between time 10 and 18 but the code is working every 30 minutes

    thanks in advance .

     public static System.Threading.Timer Timer = null;
     private static readonly int _time = DateTime.Now.Hour;

    protected override void OnStart(string [] args)
        {   
            Core.Timer = new Timer(timer_Tick, null, 0, CalculateMinute(30));  // 30 minutes    
            base.OnStart(args);

          }
      
       protected override void OnStop()
        {   
          Core.Timer.Dispose();
          Core.Timer = null;   
          base.OnStop();     
        }
     private static void timer_Tick(object sender)
        {

          if ( _time < 10 || _time > 18) return;
         
              Core.Method  //its Doing Something         
              RestartOrKillService(); // this is try to stop service and trigger to OnStop event
          }

    Tuesday, September 5, 2017 9:27 PM

Answers

  • 1) Minor problem, but normally when you override a start/init type of method, you let the base.MethodName() run before your code so you can make sure the class is in fully initialized state before your section of code runs.

    2) I think you want to check DateTime.Now.Hour instead of _time to decide when to return in timer_Tick event. The _time variable is captured only when your code start to run, and will not be changed afterwards.


    • Edited by cheong00Editor Wednesday, September 6, 2017 4:00 AM
    • Marked as answer by Aly14 Thursday, September 7, 2017 3:39 PM
    Wednesday, September 6, 2017 3:59 AM
    Answerer

All replies

  • 1) Minor problem, but normally when you override a start/init type of method, you let the base.MethodName() run before your code so you can make sure the class is in fully initialized state before your section of code runs.

    2) I think you want to check DateTime.Now.Hour instead of _time to decide when to return in timer_Tick event. The _time variable is captured only when your code start to run, and will not be changed afterwards.


    • Edited by cheong00Editor Wednesday, September 6, 2017 4:00 AM
    • Marked as answer by Aly14 Thursday, September 7, 2017 3:39 PM
    Wednesday, September 6, 2017 3:59 AM
    Answerer
  • minor problem , minor suggestion and the end major solution , Thank you so much .
    Thursday, September 7, 2017 3:39 PM