Click here to Skip to main content
15,917,522 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When I create a windows service, I add the codes to OnStart() and OnStop(), but they just work at Start and Stop service. So, what function can I put my commands to they work at RUNTIME...
Thank advance...
Posted

The simplest way to implement this is to use a timer control in you service; so that you can do some work on the timer tick for each time.


Declare following member vaiables at top.

private System.Timers.Timer ProcessTimer;
        private TimeSpan PollInterval = TimeSpan.FromMinutes(1);
        private DateTime PollTimerStopTime = DateTime.MaxValue;



On the OnStart event of the service initialize you timer like following.



protected override void OnStart(string[] args)
        {

this.ProcessTimer = new System.Timers.Timer();
                this.ProcessTimer.Interval = this.PollInterval.TotalMilliseconds;
                this.ProcessTimer.AutoReset = false;
                this.ProcessTimer.Elapsed += new System.Timers.ElapsedEventHandler(ProcessTimer_Elapsed);

//Start the timer

this.PollTimerStopTime = DateTime.MaxValue;
            this.ProcessTimer.Start();



}

Handle the ProcessTimer_Elapsed

private void ProcessTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (e.SignalTime < this.PollTimerStopTime)
            {
             //DoMyWork();
            }
}


You can find samples on this on google.
 
Share this answer
 
v2
Typically in a service all of the work is done in a worker thread. The OnStart method simply starts the thread and returns; if OnStart doesn't return in a timely fashion the service won't start properly. In the OnStop method all that needs to be done is to signal the thread to exit. The worker thread is then free to run a command processor or data consumer or whatever you need until it's told to stop.
 
Share this answer
 
Thank...
But It don't work...

Sometime it work but I expect it work repeated some commands within service active, like loop while in windows application

MIDL
while (GetMessage(....))
{
// MyWork

}
 
Share this answer
 
Thank in advance.... :)
I did it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900