Restarting a windows service after a fixed time interval - c#

I am developing a windows service that sends automated e-mail in every 15 minutes. I am using a timer to use the service again after a fixed time interval (15 minutes) but its not working.
namespace Mailer
{
public partial class Mailer : ServiceBase
{
System.Timers.Timer createOrderTimer;
public Mailer()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
sendmail(); //function to send email.
createOrderTimer = new System.Timers.Timer();
createOrderTimer.Elapsed += new System.Timers.ElapsedEventHandler(createOrderTimer_Elapsed);
createOrderTimer.Interval = 15000;
createOrderTimer.Enabled = true;
createOrderTimer.AutoReset = true;
createOrderTimer.Start();
}
protected void createOrderTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs args)
{
createOrderTimer.Stop();
ServiceController controller = new ServiceController("Mailer");
controller.Start();
}
protected void sendmail
{
//code to send email.
}
protected override void OnStop() { }
}
}
Initially the email is sent but I want the email sending to be performed in every 15 minutes.

You need to change the code like this
namespace Mailer
{
public partial class Mailer : ServiceBase
{
System.Timers.Timer createOrderTimer;
public Mailer()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
createOrderTimer = new System.Timers.Timer();
createOrderTimer.Elapsed += new System.Timers.ElapsedEventHandler(sendmail);
createOrderTimer.Interval = 900000; // 15 min
createOrderTimer.Enabled = true;
createOrderTimer.AutoReset = true;
createOrderTimer.Start();
}
protected void sendmail(object sender, System.Timers.ElapsedEventArgs args)
{
//code to send email.
}
protected override void OnStop() { }
}
}

Related

Windows Service Does Not Fire OnStart Event

I have windows service application. But the OnStart event does not fire. Only OnStop event is firing every time I stop the service. What did I miss ?
public partial class Scheduler : ServiceBase
{
private Timer timer1 = null;
public Scheduler()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer1 = new Timer();
timer1.Interval = 5000;
timer1.Elapsed += new ElapsedEventHandler(this.timer1_Tick);
}
protected override void OnStop()
{
timer1.Enabled = false;
Library.Log(String.Format("Windows service stopped"));
}
private void timer1_Tick(object sender, ElapsedEventArgs e)
{
Library.Log(String.Format("Scheduler service {0}", DateTime.Now));
}
}
OnStart is firing, your timer is not.
You must either do timer1.Start() or timer1.Enabled = true in OnStart for the timer to start firing.
protected override void OnStart(string[] args)
{
Library.Log("Windows service started");
timer1 = new Timer();
timer1.Interval = 5000;
timer1.Elapsed += new ElapsedEventHandler(this.timer1_Tick);
timer1.Start()
}

Trouble activating Timer in Windows Service

I'm currently trying to create a service that will execute a metod every 14 days, (is 20 sec now, becasue of testing). I have currently these lines of code in my service and i cant seem to get it to run the AddDataToDb() metod. Anyone got any idea of what i can do to get the timer to work?
public partial class Service1 : ServiceBase
{
System.Timers.Timer oTimer = null;
double interval = 2000;
public Service1()
{
InitializeComponent();
IntializeService();
}
void IntializeService()
{
oTimer = new System.Timers.Timer(interval);
oTimer.Enabled = true;
oTimer.AutoReset = true;
oTimer.Start();
oTimer.Elapsed += new ElapsedEventHandler(oTimer_Elapsed);
}
void oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Data.mData data = new mData();
data.AddDataToDb();
}
protected override void OnStart(string[] args)
{
oTimer.Enabled = true;
oTimer.Start();
}
protected override void OnStop()
{
oTimer.Stop();
}
}

Rerun method as soon as it has finished

Right now I'm using a timer to trigger my method. But how can I make the service run my method as soon as it has finished?
private Timer timer;
public Service()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
DoSomething();
timer = new Timer();
timer.Enabled = true;
timer.Interval = 60000;
timer.AutoReset = true;
timer.Start();
timer.Elapsed += timer_Elapsed;
}
protected override void OnStop()
{
base.OnStop();
}
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
DoSomething();
}
Get rid of the timer and use recursion:
public Service()
{
InitializeComponent();
DoSomething();
}
private void DoSomething()
{
// some code that takes a while to execute
// make recursive call to self
DoSomething();
}
EDIT The answer as accepted won't work in the context of a service (actually, it will execute, but the service itself will be forever stuck in 'Starting' status, and will generate a 1503 error).
Here is the full code for a service that will continuously execute a method:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace recursion
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
System.Threading.Thread thread;
protected override void OnStart(string[] args)
{
System.IO.File.WriteAllText(#"C:\Temp\Foo.txt", "Starting at: " + System.DateTime.Now.ToString());
thread = new System.Threading.Thread(DoSomething);
thread.Name = "Worker Thread";
thread.IsBackground = true;
thread.Start();
}
private void DoSomething() {
while (true)
{
System.IO.File.WriteAllText(#"C:\Temp\Foo.txt", "The Time is now: " + System.DateTime.Now.ToString());
System.Threading.Thread.Sleep(1000);
}
}
protected override void OnStop()
{
}
}
}
#cslecours you were wrong that it would cause a StackOverflow, but you were right in that causing the OnStart method not to exit would cause and error for a Windows service.
Use a Thread and an infinite while loop.
private void Start()
{
while(true)
DoSomething();
}
protected override void OnStart(string[] args)
{
Task.Factory.StartNew(() => Start());
}

Windows Service doesn't start based on the interval time

I wrote a windows service to call my class library every 10 mins interval,it works fine when start or restart .once the job done it suppose to re run again every 10 min's that's not happening at all.Am not sure what am missing,some one please identify the correct way.
Here is my code
public partial class Service1 : ServiceBase
{
private Timer _timer;
private DateTime _lastRun = DateTime.Now;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
_timer = new Timer(10 * 60 * 1000); // every 10 minutes
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
Shell Distribute= new Shell();
Distribute.Distribute();
}
protected override void OnStop()
{
this.ExitCode = 0;
base.OnStop();
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//if (_lastRun.Date < DateTime.Now.Date)
//{
_timer.Stop();
_lastRun = DateTime.Now;
_timer.Start();
//}
}
}
}
Your problem is compare of date if (_lastRun.Date < DateTime.Now.Date) so your code runs once a day.
I agree with Ozgur. It appears that your logic is wrong. You can just stop the timer during the timer_Elapsed event do you logic and restart timers
Something like :
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try{
// stop the timer while we are running the cleanup task
_timer.Stop();
//
// do cleanup stuff
//
}catch (Exception e){
//do your error handling here.
}
finally{
_timer.Start();
}
}
}
Just wrap it with a try catch and finally so you handle exceptions and can make sure the timer is started again. Also please review this link Best Timer for using in a Windows service
Okie Finally i got the answer,why its not working (One of the expert from other forum point out my mistake)
This the code works well based on timer interval.
public partial class Service1 : ServiceBase
{
private Timer _timer;
private DateTime _lastRun = DateTime.Now;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
_timer = new Timer(10 * 60 * 1000); // every 10 minutes
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
Shell Distribute= new Shell();
Distribute.Distribute();
_timer.start();//this line was missed in my original code
}
protected override void OnStop()
{
this.ExitCode = 0;
base.OnStop();
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//if (_lastRun.Date < DateTime.Now.Date)
//{
try
{
_timer.Stop();
Shell Distribute= new Shell();
Distribute.Distribute();
}
catch(exception ex)
{}
finally
{
_timer.Start();
}
//}
}
}
}

windows services is working only when messagebox.show is used How to avoid it

This is my code
protected override void OnStart(string[] args)
{
timAutoUpdate.Enabled = true;
MessageBox.Show("started");
}
protected override void OnStop()
{
timAutoUpdate.Enabled = false;
System.Windows.Forms.MessageBox.Show("Service stopped");
}
private void timAutoUpdate_Tick(object sender, EventArgs e)
{
MessageBox.Show("Ticked");
}
Its showing message "Ticked" after starting event.If i delete messagebox in Onstart event then Tick event is not working.Its not showing any message.Please specify the reason behind it.I just kept simple message box in Tick event instead of my code.Please tell me the way to achieve it.
protected override void OnStart(string[] args)
{
timAutoUpdate.Enabled = true;
}
protected override void OnStop()
{
timAutoUpdate.Enabled = false;
}
private void timAutoUpdate_Tick(object sender, EventArgs e)
{
MessageBox.Show("Ticked");
}
What timer are you using? is it System.Windows.Forms.Timer?
if this is the case, you need to change it because this timer does not work with Windows service (http://msdn.microsoft.com/en-us/magazine/cc164015.aspx)
Try this code:
protected override void OnStart(string[] args)
{
scheduleTimer = new System.Threading.Timer(new TimerCallback(AutoTick), null, 0, 3000);
eventLogEmail.WriteEntry("Test");
}
private void AutoTick(object state)
{
MessageBox.Show("Ticked")
}

Categories