Please look at this piece of code
public partial class TestService : ServiceBase
{
private static System.Timers.Timer aTimer;
protected override void OnStart(string[] args)
{
aTimer = new Timer(10000 * 6 * 5); // 5 minutes interval
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
......
}
}
When I start this service at say 4:00 pm, the first time OnTimedEvent is called is at 4:05 pm, then 4:10 pm and so on. I would like the OnTimedEvent to be called at 4:00 pm as soon as I start the service. Is there anything I am missing here?
Use a System.Threading.Timer rather than a System.Timers.Timer.
It has a constructor overload that in addition to specifying the interval allows you choose the start delay, which can be set to 0 to fire immediately.
For a Comparison of the timer classes, see Windows.Forms.Timer OR System.Threading.Timer (specifically 'Initial timer event schedulable?')
You could just call the event in the OnStart
OnTimedEvent(this, null)
System.Timers.Timer starts counting down from 5 minutes and then the event is triggered. So it won't be able to trigger and run the code till the timer reaches 0.
The code may be run before the event listener is enabled this way shown below:
public partial class TestService : ServiceBase
{
private static System.Timers.Timer aTimer;
protected override void OnStart(string[] args)
{
aTimer = new Timer(10000 * 6 * 5); // 5 minutes interval
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
foo();
aTimer.Enabled = true;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
foo();
}
private void foo(){
.....
}
}
Related
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.
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.
I create a windows service to run a piece of code and implemented timer in it to run it periodically.
My timer class is :
class TimerClass
{
private static System.Timers.Timer aTimer;
public static void Main()
{
aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
GC.KeepAlive(aTimer);
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
aTimer.Stop();
DatabaseUpdation dbUp = new DatabaseUpdation();
File.AppendAllText(#"C:\Documents and Settings\New Folder\My Documents\demo\abc.txt", "Start" + " " + DateTime.Now.ToString() + Environment.NewLine);
dbUp.GetDatafromSource();
aTimer.Start();
}
}
And i am calling it from my Start method:
protected override void OnStart(string[] args)
{
TimerClass timer = new TimerClass();
}
But timer is not executing at all.
Can anyone find me the mistake here?
Thanks in advance
Please, read about Constructor
your initialization code should not be in public static void Main(), but instead in public TimerClass()
class TimerClass
{
private System.Timers.Timer aTimer;
public TimerClass()
{
aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
GC.KeepAlive(aTimer);
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
aTimer.Stop();
DatabaseUpdation dbUp = new DatabaseUpdation();
File.AppendAllText(#"C:\Documents and Settings\New Folder\My Documents\demo\abc.txt", "Start" + " " + DateTime.Now.ToString() + Environment.NewLine);
dbUp.GetDatafromSource();
aTimer.Start();
}
}
also your methods and aTimer should not be static.
You need to call Main method to start timer:
protected override void OnStart(string[] args)
{
TimerClass.Main();
}
BTW not very good name - I think something like Start will be better. Also I hope this is not your app entry point method.
You forgot to start your timer. Move it outside your elapse. Elapse is only called when your timer is expired.
aTimer.Start();
FYI you don't need to enable your timer once you call the start method
Try this:
class TimerClass
{
private static System.Timers.Timer aTimer;
public static void Main()
{
aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 5000;
GC.KeepAlive(aTimer);
}
public static void Start()
{
aTimer.Start();
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
aTimer.Stop();
DatabaseUpdation dbUp = new DatabaseUpdation();
File.AppendAllText(#"C:\Documents and Settings\New Folder\My Documents\demo\abc.txt", "Start" + " " + DateTime.Now.ToString() + Environment.NewLine);
dbUp.GetDatafromSource();
aTimer.Start();
}
}
and you need to call it like this:
protected override void OnStart(string[] args)
{
//TimerClass timer = new TimerClass();<==No need it's static class!!!
TimerClass.Main();
TimerClass.Start();
}
Hello
Lets say I have a console application, that looks like this
class Program
{
static void Main(string[] args)
{
}
public void DoSomething()
{
Console.WriteLine("Hello World");
}
}
}
I wan't to execute my DoSomething method every 10'th second by using System.Threading.timer. Can anyone give an example of how that is done?
Thanks in advance :)
Timer timer1 = new Timer(10000);
timer1.Enabled = true;
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
timer1.Start();
static void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
//Do Something
}
The documentation page for the System.Threading.Timer class has a lengthy, good example.
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.