none
Windows Service - Start and Stop everyday at a particular time. RRS feed

  • Question

  • Hi,

    Below is my code which runs every minute once the Windows Service is started.

    I want this service to START every day  at a particular time (say 1:00pm) with Timer Interval every minute and STOP at a particular time ( say  10:00pm).

    Need inputs please.  Thanks.

    namespace Service
    {
        partial class WindowsService : ServiceBase
        {
            private System.Timers.Timer RefreshTimer = null;
    
            public Data_Service()
            {
                InitializeComponent();
            }
    
            protected override void OnStart(string[] args)
            {
                try
                {               
                    int refreshTimeInterval = 60000; //Default Time interval set in milliseconds          
    
                    this.RefreshTimer = new System.Timers.Timer();
                    this.RefreshTimer.Interval = refreshTimeInterval;
                   
                    this.RefreshTimer.Elapsed += RefreshTimer_Elapsed;
                    this.RefreshTimer.Start();
                }
                catch (Exception ex)
                {
                    throw ex;
                  
                }
                finally
                {
                   
                }
            }
    
            protected override void OnStop()
            {
                if (this.RefreshTimer != null)
                { this.RefreshTimer.Dispose(); }
              
            }
    
            private void RefreshTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                try
                {
                    if (this.RefreshTimer != null)
                    { this.RefreshTimer.Stop(); }
    
                    var timeToConvert = DateTime.Now;
                    var est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
                    var targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est).ToString("HH:mm");
                    var currentDateTime = DateTime.ParseExact(targetTime, "HH:mm", null, System.Globalization.DateTimeStyles.None);
    
                    var StartDateTime = DateTime.ParseExact("14:30", "HH:mm", null, System.Globalization.DateTimeStyles.None);
                    var EndDateTime = StartDateTime.AddMinutes(30);
    
                    if (currentDateTime == StartDateTime || (currentDateTime >= StartDateTime && currentDateTime <= EndDateTime))
                    {
                        // logic here
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (this.RefreshTimer != null)
                    { this.RefreshTimer.Start(); }
                }
            }
        }
    }


    Vamshi Janagama


    • Edited by Vamshi K J Monday, September 2, 2019 12:12 AM
    Monday, September 2, 2019 12:11 AM

All replies

  • I do not understand the relevance of the source code, if it is relevant then please explain how.

    You can very easily write a simple script that starts or stops the service. That is all it needs to do; you can pass an argument that determines whether the service is to be started or stopped. Then you can use the scheduler to schedule it to run.

    I do not understand why you say with Timer Interval every minute. Perhaps I totally misunderstand what you are asking. If you want the service to do something every minute then I think you already have that working. If that code was written by someone else and you need help understanding it then that is a different question.



    Sam Hobbs
    SimpleSamples.Info

    Monday, September 2, 2019 12:37 AM
  • As "Simple Samples" said, I don't think Timer is the right tool for you to restart the service itself.

    You may use a timer to shut itself down, but then the service itself is down and it won't be able to send signal to start itself again.

    Consider using task schedular script for restarting it.

    Monday, September 2, 2019 1:10 AM
    Answerer
  • Okay maybe now I understand better. Perhaps you are trying to check every minute to determine if the current time is within the specified range (time period) and then if it is in the specified range then do the work.

    I think the Timer.Interval Property supports more than a year. So you could calculate how many milliseconds there will be before 1 PM and use that for the interval and then when that occurs start doing the work but first calculate how many milliseconds there will be before 10 PM and set the timer so that when it is 10 PM it does whatever needs to be done to stop. Would that be more like what you wanted to do? It might be better to use the scheduler as has been described but doing it all in the service might work. I assume the timer does not have a security issue but I am not sure.

    What is the problem with the way you are doing it?



    Sam Hobbs
    SimpleSamples.Info

    Monday, September 2, 2019 3:31 AM
  • I think he wants to restart the service itself at defined time, with leeway of 30 minutes, then stop doing jobs after 10pm, both at the specified time zone.

    Btw, since the timer will trigger every minutes, unless you're sure the work is fast that it'll never exceed a minute, you may want to do something to guard against reentrancy.

    Monday, September 2, 2019 5:51 AM
    Answerer
  • Hi Simple Samples 

    Thank you for the inputs.  I will try to write code based on your suggestions.




    • Edited by Vamshi K J Monday, September 2, 2019 5:53 AM
    Monday, September 2, 2019 5:53 AM
  • Don't use a service for this. That is not what it is designed for. If you want to start a process at a particular time and stop it at a particular time then use a regular console application with a scheduled task. This allows you to control/change the scheduling without impacting the app. It is also a lot easier and simpler to write a console app then a service.

    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, September 3, 2019 2:27 PM
    Moderator