Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 322
  • Last Modified:

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?
0
vbhargav80
Asked:
vbhargav80
1 Solution
 
CtrlAltDlCommented:
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

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now