简体   繁体   中英

How to manually run a windows service periodically

I have a windows service that runs every 30 minutes on a server. My boss wants me to add a button in the admin section of the application that runs the service and retrieves current information. This is current code for the service....

protected override void OnStart(string[] args)
{
    _stop.Reset();
    //30 minutes = 1800000
    //5 minutes = 300000
    //1 minute = 60000
    _registeredWait = ThreadPool.RegisterWaitForSingleObject(_stop,
        new WaitOrTimerCallback(PeriodicProcess), null, 1800000, false);
}

protected override void OnStop()
{
    _stop.Set();
}

private void PeriodicProcess(object state, bool timeout)
{
    if (timeout)
    {
        // Periodic processing here
    }
    else
    {
        // Stop any more events coming along
        _registeredWait.Unregister(null);
    }
}

You should be able to start a service that isn't running using ServiceController .

using (var sc = new ServiceController("NameOfYourService", "NameOfYourServer"))
    sc.Start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM