Suspend a service at a given time during the day

Dear experts,

I have a windows service that runs continuously reading messages from an MSMQ.

Is there a way I can automatically suspend the service for 2 hours between 4 and 6 am?
vbhargav80Asked:
Who is Participating?
 
CtrlAltDlConnect With a Mentor Commented:
Yea, just use the Task Scheduler to Stop the service at 4AM and then create another Task to start the service again.

NET START <servicename>

and

NET STOP <servicename>
0
 
cookreCommented:
Do you simply want to stop, then restart it, or pause it
0
 
vbhargav80Author Commented:
Thanks everyone.
0
 
cmajkrzakCommented:
To do this from within pure C#, you can do the following code snip.  Add a reference to System.ServiceProcess to your project to use the code snip.
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceProcess;
 
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a instance of ServiceController looking for our service name
            System.ServiceProcess.ServiceController myservc = new ServiceController("DHCP Client");
 
            DateTime start, stop;
 
            while (true)
            {
                start = DateTime.Parse("4:00 PM");
                stop = DateTime.Parse("6:00 PM");
 
                //Write status to console
                Console.WriteLine("Status: " + myservc.Status.ToString());
 
                if (start < DateTime.Now && stop > DateTime.Now)
                {
                    if (myservc.Status == ServiceControllerStatus.Running)
                    {
                        myservc.Stop();
                    }
                }
                else
                {
                    if (myservc.Status == ServiceControllerStatus.Stopped)
                    {
                        myservc.Start();
                    }
                }
 
                //Wait 5 seconds, check again.
                System.Threading.Thread.Sleep(5000);
            }
        }
    }
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.