Error 1053: Service did not respond in time - c#

I created a new Windows-Service project and added it to the services using sc.exe, but I am always getting the error when I try to execute the Service.
Code in Program:
static void Main() {
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
Code in ServiceBase:
public Service1() {
InitializeComponent();
}
protected override void OnStart(string[] args) {
while(true) {
Console.WriteLine("Message all 5 sec...");
Thread.Sleep(5000);
}
}
protected override void OnStop() {
Environment.Exit(0);
}
I tried extending the Timeout in Registry(ServicesPipeTimeout), Using Threads and owning the Service but i still get the error.
Any Help is appreciated.
Kind Regards

Your service will never get out of the onStart-callback because of the endless loop you have created there. So this is blocking and will never finish.
You need to use a timer for your use-case. Just start a timer in your OnStart method and it shall run as expected:
public Service1() {
InitializeComponent();
}
public OnStart(string[] args)
{
Timer timer = new Timer();
timer.Interval = 5000; // 5 seconds
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
}
public void OnTimer(object sender, ElapsedEventArgs args)
{
Console.WriteLine("Message all 5 sec...");
}
The timer will send an event every 5 seconds and the added ElapsedEventHandler will call your OnTimer-Method.

Related

Run loop outside onStart

I'm making a service in C#.
I have the functions:
onStart();
copy();
onStop();
I was running copy() inside the onStart() function. But it was making the service status be set to starting forever, since the copy() function is a loop that runs infinitely (with a Thread.Sleep() inside), making the service unstoppable, unless I finish the proccess in Task Manager.
So, question is:
How can I get copy() to run at the end of onStart() and get onStart() not to wait for the completion of copy()?
You can start new Thread from OnStart so that your service return control back service controller.
protected override void OnStart(string[] args)
{
Thread MyThread = new Thread(new ThreadStart(Starter));
MyThread.Start();
base.OnStart(args);
}
private void Starter()
{
//Add your long running code here
}
You can also use Timer that will be started in OnStart and will keep your service running.
private System.Timers.Timer timer;
protected override void OnStart(string[] args)
{
this.timer = new System.Timers.Timer(3000); // 30000 milliseconds = 30 seconds
this.timer.AutoReset = true;
this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
this.timer.Start();
}
protected override void OnStop()
{
this.timer.Stop();
this.timer = null;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//Your code goes here
}
You can use a new Thread or use a Timer, with the code of an iteration in the Tick event.

Rerun service every x min with timer not working

I have a service that I want to run every X min using (for example) a timer.
This is not working, why? Any better way I can do this? Tried searching and didn't found anything that worked for me...The breakpoint never hits OnStop method...
static void Main()
{
WriteLine("service has started");
timer = new Timer();
timer.Enabled = true;
timer.Interval = 1000;
timer.AutoReset = true;
timer.Start();
timer.Elapsed += scheduleTimer_Elapsed;
}
private static void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
WriteLine("service is runs again");
}
public static void WriteLine(string line)
{
Console.WriteLine(line);
}
I was in a bit same situation earlier. I used the following code, it worked for me.
// The main Program that invokes the service
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
//Now the actual service
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
///Some stuff
RunProgram();
///////////// Timer initialization
var scheduleTimer = new System.Timers.Timer();
scheduleTimer.Enabled = true;
scheduleTimer.Interval = 1000;
scheduleTimer.AutoReset = true;
scheduleTimer.Start();
scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);
}
protected override void OnStop()
{
}
void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
RunProgram();
}
//This is where your actual code that has to be executed multiple times is placed
void RunProgram()
{
//Do some stuff
}
}

Event Handler Problem in Windows Service

I am going nuts. I can't figure out the problem.
I have a windows service that has a simple timer method. If I start the service, it always gives out exception at onTimerElapsed event. But If I write my XMLOperation methods in a different method(but not timer which I only need) and call it from program.cs, it works just fine. The working code is at the bottom also.
partial class DatabaseService : ServiceBase
{
Timer timer = new Timer();
public DatabaseService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer.Interval = 10000;
timer.Enabled = true;
timer.Elapsed += new ElapsedEventHandler(onElapsedTime);
timer.Start();
}
protected override void OnStop()
{
timer.Enabled = false;
}
public void onElapsedTime(object source, ElapsedEventArgs e)
{
try
{
XMLOperations operation = new XMLOperations();
operation.WebServiceFlexiCampaigns("http://www.flexi.com.tr/data/xml/pazaryeri/mobil.xml");
operation.WebServiceShopMilesCampaignsXMLRead("http://www.shopandmiles.com/xml/3_119_3.xml");
operation.WebServiceBonusCampaignsXMLRead("http://www.bonus.com.tr/apps/getcampaignxml.aspx?type=campaigns");
}
catch (Exception ex)
{
StreamWriter SW;
SW = File.CreateText("c:\\1.txt");
SW.WriteLine(ex.Message);
SW.Close();
}
}
here is the working one, but this time I could not manage to work that code in periods of time like I can do in timer event. I call test method manually from program.cs
partial class DatabaseService : ServiceBase
{
Timer timer = new Timer();
public DatabaseService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer.Interval = 10000;
timer.Enabled = true;
timer.Elapsed += new ElapsedEventHandler(onElapsedTime);
timer.Start();
}
protected override void OnStop()
{
timer.Enabled = false;
}
public void test()
{
try
{
XMLOperations operation = new XMLOperations();
operation.WebServiceFlexiCampaigns("http://www.flexi.com.tr/data/xml/pazaryeri/mobil.xml");
operation.WebServiceShopMilesCampaignsXMLRead("http://www.shopandmiles.com/xml/3_119_3.xml");
operation.WebServiceBonusCampaignsXMLRead("http://www.bonus.com.tr/apps/getcampaignxml.aspx?type=campaigns");
}
catch (Exception ex)
{
StreamWriter SW;
SW = File.CreateText("c:\\1111.txt");
SW.WriteLine(ex.Message);
SW.Close();
}
}
You can try this thread (see SamAgain response):
http://social.msdn.microsoft.com/Forums/en/clr/thread/8fbca78b-5078-4a12-8abb-4051076febbb
Hope it will work.

Passing parameter to a windows service in c#

I am creating a windows service which has to run on specific days and time. I am passing these variables using an XML document. Here is my code for passing the values
static void Main()
{
ServiceBase[] ServicesToRun;
Service1= new Service1();
//Load setting from xml and assign to variables "daysToExec" and "timeToExec"
LoadSettings();
Service1.daysToExecute = daysToExec;
Service1.timeToExecute = timeToExec;
ServicesToRun = new ServiceBase[] { Service1 };
ServiceBase.Run(ServicesToRun);
}
The code for OnStart() in Service1.cs
protected override void OnStart(string[] args)
{
timer1.Enable = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
foreach (string DayToRun in daysToExecute)
{
if (DateTime.Now.DayOfWeek.ToString().ToUpper().Equals(DayToRun.ToUpper()) && DateTime.Now.ToShortTimeString().Equals(timeToExecute))
{
Process.Start("Path to executable");
}
}
}
But this is not starting the executable. Is there something wrong with this code.
Thanks.
I got the answer atlast. I was using System.Windows.Forms.Timer and for some reason it was not at all executing the timer_tick method. After using System.Timers.Timer it worked fine.
Thanks for your comments.

Converting C# System.Timer to Threading.Timer

i have been using System.Timer to run a windows service but have come across the problem where the timer randomly doesnt fire. I checked it yesterday and it hadnt fired for over 2 hours when its meant to fire every 10 mins. I read this up on Google and apparently its a known problem, the answer being to change over to Threading.Timer. I havent used this before so was looking for some insight. My current code is as follows:
using System;
using System.Timers;
using System.ServiceProcess;
namespace Code
{
public partial class Service : ServiceBase
{
Timer timer = new Timer();
public Service()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 10000;
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
timer.Enabled = false;
// Run system code here
timer.Interval = 600000;
timer.Enabled = true;
}
}
}
Basically, this normally works fine. The system starts the timer and fires after 10 seconds. It stops the timer, does the job, resets the timer for 10 minutes and enables it. For the most part this always works, but as mentioned randomly decides to stop working, probably due to system resources etc.
If anyone can help me convert this into a Threading.Timer it would be appreciated.
Thanks,
Chris
Here's my best guess - not got time to test it, sorry :(
using System;
using System.Threading;
using System.ServiceProcess;
namespace Code
{
public partial class Service : ServiceBase
{
Timer timer;
AutoResetEvent autoEvent;
bool stopped = true;
public Service()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
stopped = false;
TimerCallback tcb = new TimerCallback(OnElapsedTime);
timer = new Timer(tcb, null, 10000, 600000);
}
protected override void OnStop()
{
stopped = true;
timer.Dispose();
}
private void OnElapsedTime(Object stateInfo)
{
if (stopped)
return;
// Run system code here
}
}
}
http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx
Scroll down to find the example.

Categories

Resources