473,602 Members | 2,764 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Windows service shutdown

I have a Windows Service that I need to put to sleep for about 10-20
minutes.

The problem is that if you try to shut it down during this time, it will
tell you that the service didn't respond in time and end up in a "Stopping"
state and there is nothing you can do until you reboot the system.

What I did to solve the problem was just set a flag in my Shutdown method
and set up a loop in my program to go to sleep for 1 minute at a time, wake
up and check the flag then go to sleep for another minute until the maximum
number of minutes have elapsed.

What I don't know is what is the duration of time that a service has to
shutdown before it gets that message, or is there a setting somewhere where
you can set it?

Thanks,

Tom
Oct 10 '08 #1
10 3233
Instead of calling Sleep(x) use AutoResetEvent. WaitOne(x, false).

This way it will sleep for x but wake up immediately if you set the event.
You can then call MyAutoResetEven t.Set() from your shutdown method and the
thread will awaken immediately.

--
Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com

Oct 10 '08 #2
On Fri, 10 Oct 2008 08:54:55 -0700, tshad <tf*@dslextreme .comwrote:
[...]
What I don't know is what is the duration of time that a service has to
shutdown before it gets that message, or is there a setting somewhere
where
you can set it?
Rather than worrying about that specific duration, you should just fix the
service so that it doesn't become unresponsive while it's sleeping (why
you feel it necessary for it to sleep "for about 10-20 minutes" is hard to
understand too, but for the moment let's assume that's actually necessary
even though it doesn't seem quite right).

From your description (it's impossible to know for sure without a
concise-but-complete code sample) in the thread that would normally
process messages for the service, you are calling something like
Thread.Sleep() with some long value. That, of course, causes the server
to fail to respond to _any_ message.

Instead of blocking that thread, you should simply be setting some state
variable that indicates that the service is in its "sleeping" state. Any
requests that come in while that flag is set can be ignored, rejected,
etc. as appropriate but you would still respond appropriately to shutdown
requests. At the same time that you set the flag, start a timer that will
clear the flag when the timer period has elapsed.

In that way, you will leave your service responsive, and it can even
shutdown properly in the middle of this "sleeping" state, but it will
still not respond to actions that you want to be suspended during the
"sleeping" state.

Pete
Oct 10 '08 #3
I think this is what service pause is for, CanPauseAndCont inue and the
OnPause event, assuming you have code somewhere to tell the service to
pause, and continue later.

--
Phil Wilson
Definitive Guide to Windows Installer
http://www.apress.com/book/view/1590592972
"tshad" <tf*@dslextreme .comwrote in message
news:ey******** ******@TK2MSFTN GP04.phx.gbl...
>I have a Windows Service that I need to put to sleep for about 10-20
minutes.

The problem is that if you try to shut it down during this time, it will
tell you that the service didn't respond in time and end up in a
"Stopping" state and there is nothing you can do until you reboot the
system.

What I did to solve the problem was just set a flag in my Shutdown method
and set up a loop in my program to go to sleep for 1 minute at a time,
wake up and check the flag then go to sleep for another minute until the
maximum number of minutes have elapsed.

What I don't know is what is the duration of time that a service has to
shutdown before it gets that message, or is there a setting somewhere
where you can set it?

Thanks,

Tom

Oct 10 '08 #4

"Peter Morris" <mr*********@SP AMgmail.comwrot e in message
news:Oy******** ******@TK2MSFTN GP04.phx.gbl...
Instead of calling Sleep(x) use AutoResetEvent. WaitOne(x, false).

This way it will sleep for x but wake up immediately if you set the event.
You can then call MyAutoResetEven t.Set() from your shutdown method and the
thread will awaken immediately.
That sounds pretty good,

I'll try that.

Thanks,

Tom
>

--
Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com

Oct 10 '08 #5

"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
On Fri, 10 Oct 2008 08:54:55 -0700, tshad <tf*@dslextreme .comwrote:
>[...]
What I don't know is what is the duration of time that a service has to
shutdown before it gets that message, or is there a setting somewhere
where
you can set it?

Rather than worrying about that specific duration, you should just fix the
service so that it doesn't become unresponsive while it's sleeping (why
you feel it necessary for it to sleep "for about 10-20 minutes" is hard to
understand too, but for the moment let's assume that's actually necessary
even though it doesn't seem quite right).
Because in this case it is a FileWatcher that is running through files and
processing them and depends on SQL Server. If Sql Server goes down
(maintenance, reboots, crashes etc), I want the Service to go to sleep for a
specified amount of time and then try again. If it is still down it will do
that again - each time sending a message that it is still getting a timeout.
I don't want it to be checking again right after it got the error over and
over again sending messages every 20 seconds.

I figure 10 minutes or so is a good duration.
From your description (it's impossible to know for sure without a
concise-but-complete code sample) in the thread that would normally
process messages for the service, you are calling something like
Thread.Sleep() with some long value. That, of course, causes the server
to fail to respond to _any_ message.
Which is why I changed the code to go to sleep for a minute, wake up and
check if the stop button was pressed. If not, it goes to sleep for another
minute until the maximum amount of minutes has gone by. If the stop button
was pressed, it exits the thread (after releasing the Mutex I am using).

Thanks,

Tom
>
Instead of blocking that thread, you should simply be setting some state
variable that indicates that the service is in its "sleeping" state. Any
requests that come in while that flag is set can be ignored, rejected,
etc. as appropriate but you would still respond appropriately to shutdown
requests. At the same time that you set the flag, start a timer that will
clear the flag when the timer period has elapsed.

In that way, you will leave your service responsive, and it can even
shutdown properly in the middle of this "sleeping" state, but it will
still not respond to actions that you want to be suspended during the
"sleeping" state.

Pete

Oct 10 '08 #6
On Fri, 10 Oct 2008 15:53:59 -0700, tshad <tf*@dslextreme .comwrote:
Because in this case it is a FileWatcher that is running through files
and
processing them and depends on SQL Server. If Sql Server goes down
(maintenance, reboots, crashes etc), I want the Service to go to sleep
for a
specified amount of time and then try again. If it is still down it
will do
that again - each time sending a message that it is still getting a
timeout.
I don't want it to be checking again right after it got the error over
and
over again sending messages every 20 seconds. [...]
But instead of making your service unresponsive, you should instead simply
have it internally defer whatever work it would normally do, based on a
timer. There's no reason to block a thread for that.

Your current "sleep for a minute then check" is definitely not the way to
go. Even Peter M.'s suggestion is less than optimal because it assumes
there's a thread somewhere that _can_ respond by setting the event
handle. It would be best to just not make the service unresponsive in the
first place.

If it were orders of magnitude harder to do it the right way than the
wrong way, I could see the lure of doing it the wrong way. But it's not
hard to set up a timer and include logic to cause normal processing to be
suspended without actually blocking a thread.

Pete
Oct 11 '08 #7
On 11 Oct, 01:11, "Peter Duniho" <NpOeStPe...@nn owslpianmk.comw rote:
On Fri, 10 Oct 2008 15:53:59 -0700, tshad <t...@dslextrem e.comwrote:
Because in this case it is a FileWatcher that is running through files *
and
processing them and depends on SQL Server. *If Sql Server goes down
(maintenance, reboots, crashes etc), I want the Service to go to sleep *
for a
specified amount of time and then try again. *If it is still down it *
will do
that again - each time sending a message that it is still getting a *
timeout.
I don't want it to be checking again right after it got the error over *
and
over again sending messages every 20 seconds. *[...]

But instead of making your service unresponsive, you should instead simply *
have it internally defer whatever work it would normally do, based on a *
timer. *There's no reason to block a thread for that.

Your current "sleep for a minute then check" is definitely not the way to*
go. *Even Peter M.'s suggestion is less than optimal because it assumes*
there's a thread somewhere that _can_ respond by setting the event *
handle. *It would be best to just not make the service unresponsive in the *
first place.

If it were orders of magnitude harder to do it the right way than the *
wrong way, I could see the lure of doing it the wrong way. *But it's not *
hard to set up a timer and include logic to cause normal processing to be*
suspended without actually blocking a thread.

Pete
Let the service handle exception by incrementing a counter each time
it fails. Report the exception only after a number of retries. Reset
the counter if it succeeds. For example the service will report the
exception only after 5 retries.

The down side to this is that you will not know if the service fails
regularly, but works after a couple of retries. So rather than
resetting the counter when it suceeds, the counter could be reset
after an hour. In other words, if fails 5 times within one hour you'll
be notified too.

Of course, the number of retries and timer duration it upto you.
Oct 11 '08 #8
Your current "sleep for a minute then check" is definitely not the way to
go. Even Peter M.'s suggestion is less than optimal because it assumes
there's a thread somewhere that _can_ respond by setting the event
handle.
Seeing as this service sleeps for X seconds and then tries to process files
but needs to postpone that work for 10 minutes if SQL Server was unreachable
I see no reason why it should wake up every X seconds just to check if it
has been terminated. We know it should not process any files for another 10
minutes so the thread only needs to resume if it is told to terminate. In
which case we just need the worker running in a 2nd thread.

--
Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com

Oct 12 '08 #9
On Sun, 12 Oct 2008 01:17:26 -0700, Peter Morris
<mr*********@sp amgmail.comwrot e:
Seeing as this service sleeps for X seconds and then tries to process
files but needs to postpone that work for 10 minutes if SQL Server was
unreachable I see no reason why it should wake up every X seconds just
to check if it has been terminated.
It shouldn't. You aren't understanding my point. The service should
never be unresponsive in the first place. Instead, use a timer to manage
tasks that need to happen on a periodic basis, leaving the main thread of
the service ready to process interruptions such as a shutdown.

One of the most annoying things in an OS is software that isn't
responsive. It delays operations like shutting the software itself down,
or shutting down the operating system, for no good reason.

It's certainly possible to address that issue in the way you suggest. But
I don't see the point in having a thread just sitting there waiting, when
you can just use a timer and not have a thread dedicated to _just_ waiting.

You seem to be taking offense to my commentary about your proposed
solution. I'm sorry if I offended you; I'm simply stating my opinion.
Your proposal is certainly better than what Tom's doing now. I just
happen to believe there's an even better approach that can be used.

Pete
Oct 12 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
7119
by: Bill Sonia | last post by:
I'm written a Windows Service to send e-mails on events like OnStart, OnStop, OnShutDown using System.Web.Mail. It works for everything but OnShutdown. My guess is that once my send mail code is executed, other necessary Windows Services have been terminated before it can actually send the mail. I've updated my HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services registry DependOnService value including SMPTSVC and others. My hope is...
8
4177
by: Bill Sonia | last post by:
I've written a Windows Service to send e-mails on events like OnStart, OnStop, OnShutDown using System.Web.Mail. It works for everything but OnShutdown. My guess is that for OnShutDown, once my send mail code is executed, other necessary Windows Services have been terminated before it can actually send the mail. I've updated my HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services registry DependOnService value including SMPTSVC and...
6
8750
by: carbon_dragon | last post by:
Ok, so here is the problem. I'm working on a headless server program implemented as a .NET C# Console project. There is a UPS mounted to this server (though not a windows compliant UPS). I can only talk to the UPS over a special device driver. Through this device driver I can detect that the UPS is going to notify Windows 2000 server to shut down. So I start doing a graceful termination. But Windows shuts down pretty quickly and there...
2
1786
by: Mr Newbie | last post by:
I have an annoying teenager who wont go to bed because he is allways on his computer. I want to write a windows service which will shut down his computer at night and not allow this to be restarted until the morning. So I have decided to try and write a windows service to do this. Stage one is to see if I can get the damn thing to shutdown so I managed to get it installed but it wont shutdown the PC. I tried the same code in a windows...
2
4095
by: Peter Meinl | last post by:
Restarting Windows seems not to fire the OnShutdown event in the Windows Service. Does not work on Windows XP SP2 and not on Windows 2003 Server SP1. OnStart and OnStop do work fine. Steps to reproduce: Create a Windows service in VB.NET using VS 2005. Set CanShutdown property to true.
0
2137
by: Stefan Krah | last post by:
Hello, I'm trying to run a Python script as a Windows service with a defined shutdown. The script (enigma-client.py) handles the communications with the server in a distributed computing effort and calls a C program (enigma.exe) to do the computations. enigma.exe should save its current state when receiving SIGINT or SIGTERM. This (obviously) works under Unix and also when running the script from the Windows command line and...
0
1163
by: Mathew Clark | last post by:
I'm trying to write a Windows Service that is capable of detecting when a shutdown is occurring, and cancelling it. I've managed to get this to work fine in a windows application, using SystemEvents.SessionEnding, like so: - Private Sub MyBase_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load AddHandler SystemEvents.SessionEnding, AddressOf
6
9512
by: Ash | last post by:
Hi coders, I have a service that does alot of data copying to the database and when the service is stopped or the machine is shutting down it commits the data (in addition to other things) and makes sure it exists gracefully (this could take upto 5-6 mins). I tried increasing HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\WaitToKillServiceTimeout to 5 mins (300000) on a test service that sleeps for 4 mins when OnStop/Shutdown is...
4
1950
by: jez123456 | last post by:
Hi Experts I've written a c# windows service which runs another program at certain intervals. The other program may take upto 20 minutes to complete it's tasks. My question is what happens to the other program if a user decides to manually stop the service (or there was a power cut) when the tasks have not fully completed? Should I wrap the other program within a transaction?
0
7993
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7920
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8054
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8268
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
5867
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5440
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3900
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1510
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.