I've got this code in a Windows Service:
public void ConfigureService()
{
//timer = new Timer { Interval = 600000 };
timer = new Timer { Interval = 10000 };
// 10 minutes; 1 second while testing
timer.Elapsed += timer_Tick;
timer.Enabled = true;
RoboRprtrLib.WriteToLog("RoboRprtrService has started");
}
private void timer_Tick(object sender, ElapsedEventArgs eeargs)
{
timer.Elapsed -= timer_Tick;
try
{
RoboRprtrLib.WriteToLog("Timer has ticked");
RoboRprtrLib.GenerateAndEmailDueReports();
}
finally
{
timer.Elapsed += timer_Tick;
}
}
ConfigureService() is called from Program.cs:
static void Main()
{
// got this idea ("How to Debug or Test your Windows Service Without Installing it...") from http://www.codeproject.com/Tips/261190/How-to-Debug-or-Test-your-Windows-Service-Without
#if(!DEBUG)
var ServicesToRun = new ServiceBase[]
{
new RoboRprtrService()
};
ServiceBase.Run(ServicesToRun);
#else
var rrs = new RoboRprtrService();
rrs.ConfigureService();
#endif
}
I have a breakpoint in ConfigureService() on this line:
timer = new Timer { Interval = 10000 };
It is reached; I can step through the entire ConfigureService() method.
I have a breakpoint in the Elapsed/Tick event on the first line:
timer.Elapsed -= timer_Tick;
...and it is never reached.
Why not? Isn't the timer set to trip after 10 seconds, at which point the Tick event handler should be called?
UPDATE
This is the entire code for the class deriving from ServiceBase:
public partial class RoboRprtrService : ServiceBase
{
private Timer timer;
public RoboRprtrService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
ConfigureService();
}
public void ConfigureService()
{
//timer = new Timer { Interval = 600000 };
timer = new Timer { Interval = 50000 };
// 10 minutes; 50 seconds while testing
timer.Elapsed += timer_Tick;
timer.Enabled = true;
RoboRprtrLib.WriteToLog("RoboRprtrService has started");
}
private void timer_Tick(object sender, ElapsedEventArgs eeargs)
{
timer.Elapsed -= timer_Tick;
try
{
RoboRprtrLib.WriteToLog("Timer has ticked");
RoboRprtrLib.GenerateAndEmailDueReports();
}
finally
{
timer.Elapsed += timer_Tick;
}
}
protected override void OnStop()
{
timer.Enabled = false;
RoboRprtrLib.WriteToLog("RoboRprtrService has stopped");
}
}
UPDATE 2
It seems odd to me, but if I add this line:
RoboRprtrLib.GenerateAndEmailDueReports();
...to the end of the ConfigureService() method, the timer is eventually tripped.
UPDATE 3
More oddities: I was getting err msgs about needing to add the STAThread attribute (and a method was being called that shouldn't have been, which caused it to fail and the service to crash). So I decorated Main() in Program.cs with "[STAThread]" and now it works as it should.
The timer tripped several times during the operation, but I have code to exit if processing is occurring. When the called method completed, the IDE "flashed" as if to say, "Poof! I'm outta here!"
So my Program.cs code is now:
[STAThread]
static void Main()
{
#if(!DEBUG)
var ServicesToRun = new ServiceBase[]
{
new RoboRprtrService()
};
ServiceBase.Run(ServicesToRun);
#else
var rrs = new RoboRprtrService();
rrs.ConfigureService();
Console.ReadLine();
#endif
}
...and the most pertinent code in the class that derives from ServiceBase is:
public void ConfigureService()
{
//timer = new Timer { Interval = 600000 };
timer = new Timer { Interval = 50000 };
// 10 minutes; 50 seconds while testing
timer.Elapsed += timer_Tick;
timer.Enabled = true;
RoboRprtrLib.WriteToLog("RoboRprtrService has started");
operationIsRunning = true;
RoboRprtrLib.GenerateAndEmailDueReports();
operationIsRunning = false;
}
private void timer_Tick(object sender, ElapsedEventArgs eeargs)
{
if (operationIsRunning) return;
operationIsRunning = true;
. . .
The "if (operationIsRunning) return;" breakpoint in the tick handler was reached three times during my last run while GenerateAndEmailDueReports() was executing, and each time it, as designed, returned.
As Hans Passant said in comments, in debug mode you code will terminate immediately after calling ConfigureService, so there is no time for the timer to be executed.
In release mode ServiceBase.Run blocks the thread until the service has finished, but this doesn't happen in debug version.
EDIT:
Actually I tried with Console.ReadLine() and did not stop, apparently standard input is redirected, just try to keep the process running, with an infinite loop or something.
Like this:
static void Main()
{
// got this idea ("How to Debug or Test your Windows Service Without Installing it...") from http://www.codeproject.com/Tips/261190/How-to-Debug-or-Test-your-Windows-Service-Without
#if(!DEBUG)
var ServicesToRun = new ServiceBase[]
{
new RoboRprtrService()
};
ServiceBase.Run(ServicesToRun);
#else
var rrs = new RoboRprtrService();
rrs.ConfigureService();
while (true)
Thread.Sleep(100);
#endif
}
Related
In my Xamarin App, I want to set the timer interval for timer e.g. Start after 5 seconds and run for 10 seconds.
Here is my code sample
Device.StartTimer(TimeSpan.FromSeconds(5), () =>
{
FaceIdentityInstruction = "Look Down";
return false;
});
You could add System.Timers after Device.StartTimer 5 seconds.
private static System.Timers.Timer aTimer;
static int count = 0;
public PageListView()
{
InitializeComponent();
Console.WriteLine("Timer prepare for running");
Device.StartTimer(TimeSpan.FromSeconds(5), () =>
{
Console.WriteLine("Timer run");
aTimer = new System.Timers.Timer(1000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
return false;
});
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
count++;
if (count==10)
{
aTimer.Stop();
Console.WriteLine("Timer Stop");
}
}
The output:
10-23 10:34:14.250 I/mono-stdout(29128): Timer prepare for running
10-23 10:34:19.262 I/mono-stdout(29128): Timer run
10-23 10:34:29.286 I/mono-stdout(29128): Timer Stop
basically I'm trying to implement the timer in class for my would-be very first game in C#; I want to use timers that will constantly update the player and provide certain periodic feedback, but I can't seem to get the 'timer' class to work correctly. If I use it in a loop (as shown below), it will wait 2 seconds, and then keep writing "You're Alive!" to the console with 0 delay in-between; and if I do not use the loop, the application just ends instantly.
using System;
using System.Timers;
public class MyClass
{
public static void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("You're alive!");
}
public static void Main(String[] args)
{
while (true)
{
Timer MyTimer = new Timer();
MyTimer.Interval = 2000;
MyTimer.Enabled = true;
MyTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
MyTimer.Start();
}
}
Just add below line after MyTimer.Start();
Console.ReadLine();
static void Main(String[] args)
{
Timer MyTimer = new Timer();
MyTimer.Interval = 2000;
MyTimer.Enabled = true;
MyTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
MyTimer.Start();
Console.ReadLine();
}
private static void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("You're alive!");
}
I have tried to run the service every 1 minute and i have succeeded in doing so but the problem is its starting every minute regardless of the completion of the program. I have written it like this
private Timer _timer;
private DateTime _lastRun = DateTime.Now.AddDays(-1);
public SpotlessService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_timer = new Timer(1 * 60 * 1000); // every 1 hour
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start();
}
public void Start()
{
OnStart(new string[0]);
}
void timer_Elapsed(object sender, EventArgs e)
{
Util.LogError("Started at" + DateTime.Now + "");
FileDownload objdwn = new FileDownload();
}
I have hosted it as a service and FileDownload class constructor will download some files from server and will copy the data into the database which will take like 10-15 minutes. So what i need to do is i should stop the timer till these fifteen minutes and the service should start again and should wait for the next minute and do the same thing. is this possible or should i just increase the timer value to greater extent
Stop() the timer at the beginning of the Elapse event and Start() the timer at the end. Also ensure your timer object does not get garbage collected.
private Timer _timer;
private DateTime _lastRun = DateTime.Now.AddDays(-1);
public SpotlessService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_timer = new Timer(1 * 60 * 1000); // every 1 minute
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start();
}
public void Start()
{
OnStart(new string[0]);
}
void timer_Elapsed(object sender, EventArgs e)
{
_timer.Stop();
Util.LogError("Started at" + DateTime.Now + "");
FileDownload objdwn = new FileDownload();
_timer.Start()
}
My suggestion is to use Task to perform download and call the main method again as soon as it is finished.
public void mainMethod()
{
Thread.Sleep(60000);
doDownload();
}
public void doDownload()
{
Task.Factory.StartNew(() => {
// Background download
}).ContinueWith(task => mainMethod());
}
This will allow you to perform any additional operations in the main thread if needed while the download is in progress.
OR
You can just stop the timer and run again as soon as the download is done
void timer_Elapsed(object sender, EventArgs e)
{
_timer.Stop();
Util.LogError("Started at" + DateTime.Now + "");
FileDownload objdwn = new FileDownload();
_timer.Start();
}
Basically i have a problem with this timer program I am trying to put together. On starting the program it will utilise a steady 25% CPU which i dont mind, but every time the timer fires it adds another 25% on to the CPU so on the 4th pass im completely maxed out.
I take it I'm not disposing of the timer correctly after it has fired but im new to c# and not really sure how to go about this.
the cope of my program is basically:
Execute some procedures - once completed start timer
Wait until timer elapses then start procedures again, disabling the timer until completed
any help would be greatly appreciated :)
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
IpCheck();
}
private static void EnableTimer()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
// Set the Interval to x seconds.
aTimer.Interval = 10000;
aTimer.Enabled=true;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = false;
aTimer.Dispose();
}
ok revised version below - simplified and ruled out the ip check so all it does now is show a message box - this will not even execute anymore :(
public class Timer1
{
System.Timers.Timer aTimer = new System.Timers.Timer();
public static void Main()
{
Timer1 tTimer = new Timer1();
tTimer.EnableTimer();
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
aTimer.Enabled = false;
MessageBoxPrint();
aTimer.Enabled = true;
}
private void EnableTimer()
{
// Set the Interval to x seconds.
aTimer.Interval = 10000;
aTimer.Enabled=true;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
}
public static void MessageBoxPrint()
{
MessageBox.Show("Testing");
}
}
You're probably looking for something like this:
private static System.Timers.Timer aTimer = new System.Timers.Timer();
// This method will be called at the interval specified in EnableTimer
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
aTimer.Enabled = false; // stop timer
IpCheck();
aTimer.Enabled = true; // restart timer so this method will be called in X secs
}
private static void EnableTimer()
{
// Set the Interval to x seconds.
aTimer.Interval = 10000;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled=true; // actually starts timer
}
I don't quit get, why you have the cpu load, but I would do:
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
((Timer)source).Enabled = false;
IpCheck();
((Timer)source).Enabled = true;
}
and don't dispose the timer in the method call.
The problem is that he is creating a Timer1 inside the Timer1 class so when you load Timer1, it loads another Timer1 which loads another timer1 which loads.... It think you get it
public class Timer1
{
System.Timers.Timer aTimer = new System.Timers.Timer();
public static void Main()
{
Timer1 tTimer = new Timer1();//<-this line right here is killing you
//remove it, as I don't see anyuse for it at all
then in this line
tTimer.EnableTimer();
just say
EnableTimer();
//or
this.EnableTimer();
You don't need to instantiate the class you are working in, as far as it is concerned it is already instantiated.
static System.Timers.Timer aTimer = new System.Timers.Timer();
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
aTimer.Enabled=false;
IpCheck();
aTimer.Enabled=true;
}
private static void EnableTimer()
{
// Set the Interval to x seconds.
aTimer.Interval = 10000;
aTimer.Enabled=true;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
}
private static void DisableTimer()
{
aTimer.Elapsed -= new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = false;
}
NOT TESTED NOT COMPILED, just a sample what i would do in your place, all the added lines are there without no tabs
I created a windows service with a timer in it, where I need to set set the interval after each Elapsed timer event. For example, I'd like it to fire on the hour every hour.
In Program.cs:
namespace LabelLoaderService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
static void Main()
{
#if (!DEBUG)
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new LabelLoader()
};
ServiceBase.Run(ServicesToRun);
#else
LabelLoader ll = new LabelLoader();
ll.Start();
#endif
}
}
}
In LabelLoader.cs:
namespace LabelLoaderService
{
public partial class LabelLoader : ServiceBase
{
System.Timers.Timer timer = new System.Timers.Timer();
public LabelLoader()
{
InitializeComponent();
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}
protected override void OnStart(string[] args)
{
SetTimer();
}
public void Start()
{
// Debug Startup
SetTimer();
}
public void SetTimer()
{
DateTime nextRunTime = GetNextRunTime();
var ts = nextRunTime - DateTime.Now;
timer.Interval = ts.TotalMilliseconds;
timer.AutoReset = true; // tried both true & false
timer.Enabled = true;
GC.KeepAlive(timer); // test - no effect with/without this line
}
void timer_Elapsed(object source, ElapsedEventArgs e)
{
timer.Enabled = false;
// do some work here
SetTimer();
}
If I installutil this onto my local machine, it correctly determines the next run time and executes. But it doesnt run anytime after that. If I restart the service it runs the next scheduled time and then nothing again. Is there an issue calling SetTimer() at the end of my processing to reset the Interval and set timer.Start()?
use System.Threading.Timer instead - in my experience it is more suited for server-like use...
EDIT - as per comment some code/hints:
the following is a very basic way to avoid reentry (should work ok in this specific case) - better would be some lock/Mutex or similar
make nextRunTime an instance field
create/start your time with for example
// first the TimerCallback, second the parameter (see AnyParam), then the time to start the first run, then the interval for the rest of the runs
timer = new System.Threading.Timer(new TimerCallback(this.MyTimerHandler), null, 60000, 30000);
create your timer handler similar to
void MyTimerHandler (object AnyParam)
{
if ( nextRunTime > DateTime.Now)
return;
nextRunTime = DateTime.MaxValue;
// Do your stuff here
// when finished do
nextRunTime = GetNextRunTime();
}