Timer with windows service - Please help

H

hnkien

Hi,
I am writing a windows service with threading.timer for 10 seconds but
it didn't work. Here are my code:

namespace SchedulerService
{
public class ScheduleService : System.ServiceProcess.ServiceBase
{
private System.ComponentModel.IContainer components;
protected System.Threading.Timer tmrThreadingTimer;

public ScheduleService()
{
InitializeComponent();
tmrThreadingTimer = new System.Threading.Timer(new
TimerCallback(tmrThreadingTimer_TimerCallback), null,
System.Threading.Timeout.Infinite, 1000);
}

[STAThread]
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new
ScheduleService() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}

private void InitializeComponent()
{
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.ServiceName = "SchedulerService";
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

protected override void OnStart(string[] args)
{
tmrThreadingTimer = new System.Threading.Timer(new
TimerCallback(tmrThreadingTimer_TimerCallback), null, 0, 10 * 1000) ;
//run 10 second each time
}

protected override void OnStop()
{
tmrThreadingTimer.Change(System.Threading.Timeout.Infinite,
System.Threading.Timeout.Infinite);
}

private void tmrThreadingTimer_TimerCallback(object state)
{
Console.WriteLine("I am running");
}

}

Any help?
 
G

Guest

Hi,

Just a quick question.. How do you expect to get information into the
console??
The reason I ask this is simple. You cannot run a Windows Service without
having to install it using RegSvc (to install the service) and then Net Start
(to start the service). If you try to run a service from inside the VS.NET
IDE and wait long enough(about 20-30 seconds) you will get an error stating
that it must be installed etc...

Hope this helps a little...
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

How it's not working?

In the other hand you create the timer twice once in the constructor and
another in the OnStart()

Remove one ( I would remove the one in the constructor )

Then install the service in debug mode, attach the debugger to the process
and put a breakpoint in the timer method, if it does stop it's working ,
only that you cannot use the console

No sure now where the console output goes in this case.

Cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top