Use of console.readline() - c#

now I have a C# application, which runs 24/7 with a timer, which elapse all 30 seconds and do anything.
I want to make this application to a windows service, to run in the background. But the service crash immediately..
My code:
public static System.Timers.Timer _timer = new System.Timers.Timer();
static void Main(string[] args)
{
_timer.Interval = 30000;
_timer.Elapsed += timerCallback;
_timer.AutoReset = true;
_timer.Start();
}
public static void timerCallback(Object sender, System.Timers.ElapsedEventArgs e)
{
// Do anything..
}
And the error:
Windows could not start the Application service on Local Computer.
Error 1053: The service did not respond to the start or control request in a timely fashion
In the windows event viewer this message occured:
A timeout was reached (30000 milliseconds) while waiting for the Application service to connect.
But the error appear faster than 30 seconds?!
Any solutions to run the service??
Thanks
Michael

You could use a Timer to execute the logic periodically within windows service,
protected override void OnStart(string[] args)
{
base.OnStart(args);
Timer timer = new Timer();
timer.Interval = 30*1000;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
timer.Start();
}
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
//put logic here that needs to be executed for every 30sec
}

Related

Timer in WCF server gets duplicated every time

I have a WCF service that I host in Windows Azure. I use a Timer in this server and every 10 seconds the server needs to update something. The server is implemented in a ASP application and a WPF application.
When I initialize the Timer in the contructor like this:
public Service1()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(WCFService_Elapsed);
timer.Interval = 10000;
timer.Enabled = true;
timer.Start();
}
The timer will be started but if I restart the application the timers will run faster(because it runs a duplicate of the timer). Declare the timer above the contructor as a private property doesn't do the trick.
I already tried to use it in the OnStart method from the ServiceBase class:
private System.Timers.Timer timer;
protected override void OnStart(string[] args)
{
timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(WCFService_Elapsed);
timer.Interval = 10000;
timer.Enabled = true;
timer.Start();
}
But this get never called... I also tested a static timer but that does not get started either.
What am I doing wrong?
Timer inherits IDisposable, which means Timer can and should be disposed.
I am surprised that when closing your service the timer is still running, but you should dispose at when stopping the service to fix your problem.
So in your OnStop Method you should call:
timer.Stop();
timer.Dispose();

Timer Does Not Fire Before Application Ends in C#

I have simple Console application in C# that creates a timer to write text to the Console. Then it waits for the user to press a key.
If the user presses a key before five seconds elapse, then the application ends, and the timer never fires. If the user does not press a key, then the timer fires as expected.
Why does the thread that the timer creates not keep the application from terminating? How should I ensure that the application keeps running even if the user presses a key?
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer(5000);
timer.Interval = 5000; // 5 seconds
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
timer.AutoReset = true;
timer.Start();
Console.ReadKey();
}
public static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("Timer Fired.");
}
To get the timer message to always write out, you can have the main thread wait on a reset event that is signaled once the timer is fired.
static ManualResetEvent timerFired = new ManualResetEvent(false);
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer(5000);
timer.Interval = 5000; // 5 seconds
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
timer.AutoReset = true;
timer.Start();
Console.ReadKey();
// This call will return only after timerFired.Set() is
// called. So, if the user hits a key before the timer is
// fired, this will block for a little bit, until the timer fires.
// Otherwise, it will return immediately
timerFired.WaitOne();
}
public static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("Timer Fired.");
timerFired.Set();
}
As for the other question, why doesn't it prevent the application from exiting, I'll take a stab. The timer_Elapsed() is being called from a background thread. According to MSDN, background threads don't keep the execution environment running. There's a nice discussion here.
ThreadPool threads are background threads, and MSDN Timer documentation indicates that the Timer's Elapsed event is raised on a ThreadPool thread, so the application wouldn't wait for it as it's not a foreground thread.

C# Windows Service While loop

I have a problem with a windows service.
protected override void OnStart(string[] args)
{
while (!File.Exists(#"C:\\Users\\john\\logOn\\oauth_url.txt"))
{
Thread.Sleep(1000);
}
...
I have to wait for a particular file, thus while loop is necessary, but the service will not be able to start with loop like this. What I can do to have a running service and a mechanism that checks if a file exists ?
The best option is to have a timer System.Timers.Timer in your service.
System.Timers.Timer timer = new System.Timers.Timer();
In the constructor add the handler for the Elapsed event:
timer.Interval = 1000; //miliseconds
timer.Elapsed += TimerTicked;
timer.AutoReset = true;
timer.Enabled = true;
Then in the OnStart method start that timer:
timer.Start();
In the event handler do your work:
private static void TimerTicked(Object source, ElapsedEventArgs e)
{
if (!File.Exists(#"C:\Users\john\logOn\oauth_url.txt"))
return;
//If the file exists do stuff, otherwise the timer will tick after another second.
}
A minimal service class will look somewhat like this:
public class FileCheckServivce : System.ServiceProcess.ServiceBase
{
System.Timers.Timer timer = new System.Timers.Timer(1000);
public FileCheckServivce()
{
timer.Elapsed += TimerTicked;
timer.AutoReset = true;
timer.Enabled = true;
}
protected override void OnStart(string[] args)
{
timer.Start();
}
private static void TimerTicked(Object source, ElapsedEventArgs e)
{
if (!File.Exists(#"C:\Users\john\logOn\oauth_url.txt"))
return;
//If the file exists do stuff, otherwise the timer will tick after another second.
}
}
I would consider using FileSystemWatcher as that is exactly what it is intended for, to monitor changes on the filesystem. Once event is raised on a folder, you can check if that particular file exists.
The default example in MSDN actually shows monitoring of .txt file https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx

WCF+ timer. A bad practice?

I would like for my service to be able to initiate communication with other services.
In order for it to act like a client and start the communication, I thought that an initialized in the constructor timer that calls a method every x seconds could be a good idea.
Is it a bad idea?
I can't see what could be wrong with this approach.
You could utilize System.Timers.Timer - https://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.110%29.aspx
Set its Interval to value at which you want to raise Elapsed event of timer. Subscribe to Elapsed event using an event handler which you implement, in which you would communicate with the external service.
Edit: simple example
class Program
{
private static void timer_ElapsedEventHandler(object sender, EventArgs e)
{
// communicate to external service
Console.WriteLine("ElapsedEventHandler fired");
}
static void Main(string[] args)
{
var timer = new System.Timers.Timer();
timer.Interval = 3000;
timer.Elapsed += timer_ElapsedEventHandler;
timer.Start();
Console.WriteLine("Timer started");
Console.ReadLine();
}
}

Force Window Service to stop/restart if it runs for about 30 mins

I wonder how i can force my window service to restart or stop if it's running for already about 30 mins.
it's like:
if(service.runs == 30 mins){
service.stop()
or
service.restart()
}
by the way, I am using C# on this. And I am using a Thread here.
This is how my OnStart looks like:
Thread myThread;
protected override void OnStart(string[] args){
myThread = new Thread(new ThreadStart(this.myThreadFunction));
myThreadFunction.Start();
}
Please help.
Thanks
You need to run timer on service start. And set its elapsed event to 30 mins. If it is elapsed then you can apply your above check of stopping it. You also need to Reset your timer when ever the service is stopped/restarted.
//somewhere in your class
System.Timer.Timer tmr = new System.Timers.Timer();
//on construct or start event
tmr.Interval = 1800000; //30 minutes = 60*1000*30
tmr.Elapsed -= new ElapsedEventHandler(OnTimedEvent);
tmr.Elapsed += new ElapsedEventHandler(OnTimedEvent);
tmr.Start();
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
tmr.Stop();
ServiceController service = new ServiceController(yourserviceName);
service.Stop();
// service.Start() uncomment this line if your want to restart
}
protected override void OnStop()
{
}

Categories

Resources