System.Timers Timer not firing event - c#

I have to start timer on the event when eyes are closed for a certain duration.If timer is elapsed Screen turns Off.If eye open before timer is elapsed timer is stopped and screen turns On.
ComputationOfTimer(); monitors whether eyes are open/closed. This is working fine as I am getting right feedback in console.
private void ComputationOfTimer()
{
if (blink[0] == 100) //If eye Closed detected
{
ctrlTimerStop = 3;
ctrlTimerStart = ctrlTimerStart - 1;
System.Console.Write("\n\t Eyes Closed");
timerStarting();
}
else //If eyes are open before timer is elapsed
//we have to stop timer
{
ctrlTimerStart = 5;
ctrlTimerStop -= 1;
//System.Console.Write("\n\t\t\t\t\t Opened");
timerStopping();
}
}
timerStarting() starts the timer
public void timerStarting()
{
if (ctrlTimerStart == 0)
{
screenOffTimer.Interval = 3000;
screenOffTimer.Elapsed += screenOffTimer_Tick_ScreenOff;
screenOffTimer.AutoReset=false;
if (!screenOffTimer.Enabled) //Starts timer only once
{
screenOffTimer.Enabled = true;
System.Console.Write("Timer Chaloo Hai");
}
}
}
Logic of Screen Off and Sleep
void screenOffTimer_Tick_ScreenOff(object sender, EventArgs e)
{
System.Console.Write("Eyes Closed For long time bro!");
Beep(440, 1000); // Concert A, for 1 second
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_OFF);
//as eyes are still closed send pc to Sleep start one more timer
gotoSleepTimer.Interval = 10000;
gotoSleepTimer.Elapsed += gotoSleepTimer_Tick_SleepOff;
gotoSleepTimer.AutoReset = false;
if (!gotoSleepTimer.Enabled)
{
gotoSleepTimer.Start();
}
}
void gotoSleepTimer_Tick_SleepOff(object sender, EventArgs e)
{
System.Console.Write("So rahe hain bhai ab");
Beep(440, 2000); // Concert A, for 1 second
System.Windows.Forms.Application.SetSuspendState(PowerState.Suspend, false, false);
}
timerStopping(); to stop the timer if Eyes are opened earlier
public void timerStopping() //To stop timer when Eyes Open
{
if (ctrlTimerStop == 0)
{
//to do timer stop logic
if (screenOffTimer.Enabled)
{
screenOffTimer.Stop();
System.Console.Write("Timer Band Ho Gaya");
}
//System.Windows.MessageBox.Show("Timer Stopped");
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, MONITOR_ON);
if (gotoSleepTimer.Enabled)
{
gotoSleepTimer.Stop();
}
}
}
Timer is not firing even after time is elapsed.I tried DispatcherTimer before but that is to update WPF UI and I have different objective.
Declaration part:
System.Timers.Timer screenOffTimer = new System.Timers.Timer();
System.Timers.Timer gotoSleepTimer = new System.Timers.Timer();

try
EventTabTimer.Elapsed += new ElapsedEventHandler(gotoSleepTimer_Tick_SleepOff);

I could not see screenOffTimer.Start() in the code attached in question. May be thats the problem
Thanks

Related

How to delay a timer from running or start it based on current date time

I have console application am using as demo to an App, it prints "hello", based on the timespan its expected to alert the user. when its not yet the timespan, i want to delay the app from printing hello and resume when its time.
public static async void timeCounter(int delae)
{
//This is suppose to cause a delay but it instead initiate the
//TimerOperation_Tick method.
await Task.Delay(delae);
// timer countdown
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000; // 1 second
timer.Elapsed += new ElapsedEventHandler(TimerOperation_Tick);
timer.Start();
if (obj.SubmissionCheck == true)
{
timer.Stop();
}
}
/// the event subscriber
private static void TimerOperation_Tick(object e, ElapsedEventArgs args)
{
if (timeFrame != 0)
{
Console.WriteLine("hi" + timeFrame);
timeFrame --;
if (timeFrame < 1)
{
obj.SubmissionCheck = true;
nt.Remove(obj);
startNotification();
}
}
}
Try setting timer.Enabled = false; This will prevent the timer ticks from occurring.

Timer does not fire in a multi-thread form

I have a System.Timers.Timer timer in a form. Also I have a thread that reads from an RFID device (with function: GetData()). I want to limit the time of my thread with a timer, but the timer does not fire.
System.Threading.Thread GetData;
System.Timers.Timer timer = new System.Timers.Timer();
int reverseCounter=1000;
public CardDragMaifareFrm()
{
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Interval = 10;
timer.Enabled = true;
timer.Start();
GetData = new Thread(new ThreadStart(ReadCardData));
GetData.Start();
}
void timer_Elapsed(object sender, EventArgs e)
{
if (reverseCounter > 0)
{
MessageBox.Show("hey");
reverseCounter -= 1;
}
else
{// some actions for terminating GetData thread}
}
but I don't see "hey" message... can anybody help me? thanx
I used the first rule of computer engineering: Restart it, maybe it will work"... ;-)

System.Timers.Timer() Firing multiple times due to aggregation of Elapsed Events

I want to have a section of my code start a timer once it's called, and I want this timer to keep running until I quit the whole program. My problem is, each time I call OnSomethingHappens() , the Elapsed events aggregate (despite my effort with -= ) and the timer starts firing one extra time (or at least this is what I think is happening). I have also tried defining the timer within the class, to no avail. Here's the related part of my code:
public override void OnSomethingHappens()
{
Timer aTimer= new System.Timers.Timer();
aTimer.Elapsed -= (sender, e) => DoSomethingElse(sender, e);
aTimer.Stop();
aTimer.Close();
aTimer.Elapsed += (sender, e) => DoSomethingElse(sender, e);
aTimer.Interval = 1000;
aTimer.AutoReset = true; // I want the timer to keep working, but only fire once each time
Console.WriteLine("Enabling Timer aTimer");
aTimer.Start();
}
I cannot use static (not sure how that would help but I saw timers being defined as static in many sources) because this class has many instances, and I want them to have separate timers.
Thank you.
Start your timer without the AutoReset and restart it at the end of the DoSomethingElse.
aTimer.AutoReset = false;
aTimer.Start();
DoSomethingElse(..)
{
// do stuff here
aTimer.Start();
}
if each instance of this class uses his own timer , so static is no needed.
private Timer _aTimer;
public void OnSomethingHappens()
{
if (_aTimer != null)
{
_aTimer.Enabled = true; // start timer
return;
}
_aTimer = new System.Timers.Timer();
_aTimer.Elapsed += DoSomethingElse;
_aTimer.Interval = 1000; // every 1 second
_aTimer.Enabled = true; // start timer
}
private void DoSomethingElse(object sender, ElapsedEventArgs e)
{
_aTimer.Enabled = false; // stop timer
// do w/e you want
}
First thing you should really only create once instance of the timer, and hook up one event listener. With your current code, a new timer is being created, with an event listener, every time the method is called. Instead make the timer a class variable, and hook up the event listener in the constructor.
You can start the timer in the OnSomethingHappens, but what do you want to happen on subsequent calls to the method? Should the timer restart, or just continue?
You would probably also want to make the class IDisposable, or at least provide a Stop method to stop the timer when the application closes.
public class MyClass : MyBaseClass, IDisposable
{
private Timer _timer;
private volatile bool _isStopped = true;
public MyClass()
{
_timer = new Timer();
_timer.Interval = 1000;
_timer.Elapsed = OnTimerElapsed;
}
public void Stop()
{
_isStopped = true;
_timer.Stop();
}
public void Dispose()
{
if (_timer != null)
{
Stop();
_timer = null;
}
}
protected override void OnSomethingHappens()
{
if (_timer.Enabled)
{
// Restart or do nothing if timer is already running?
}
else
{
_isStopped = false;
_timer.Start();
}
}
private void OnTimerElapsed(object sender, EventArgs a)
{
if (_isStopped)
{
// If the Stop method was called after the Elapsed event was raised, don't start a long running operation
return;
}
}
}

program will not stop sleeping computer

My application is set to go to sleep when a notification balloontip is clicked and this process is all looped. This works, but when I awaken my computer, it goes to sleep shortly thereafter (this has a slight time delay, but as this takes as long as it normally takes for my computer to go to sleep, I wouldn't give this any consideration). I've removed this snippet from my overall program, and the program then works perfectly fine, making me think that there's something in this code that makes the computer go to sleep. Furthermore, in case one of the flags controlling the loops is reset, I've reset those flags, but the problem keeps happening. In case (for some strange reason) the boolean operators were impacting it, I've changed them in all the combinations I could, and it still didn't work! I've tried adding in a command to prevent the computer from going to sleep, but that didn't work either. Any suggestions? Much appreciated.
for (; ; )
{
bool for3 = false;
for (; ; )
{
notifyIcon.ShowBalloonTip(10000);
System.Threading.Thread.Sleep(10000);
Application.DoEvents();
if (loopVariable)
for3 = true;
if (for3) break;
System.Threading.Thread.Sleep(60000);
}
loopVariable = false;
for3 = false;
DateTime timeOnSleep = DateTime.Now;
Application.SetSuspendState(PowerState.Suspend, false, false);//this is the annoying code
DateTime timeOnWake = DateTime.Now;
TimeSpan time = timeOnWake - timeOnSleep;
var minutes = time.TotalMinutes;
Math.Round(time.TotalMinutes, MidpointRounding.AwayFromZero);
double dMins = minutes;
try
{
int iNumber = System.Convert.ToInt32(dMins);
}
catch (System.OverflowException)
{
if (dMins >= 40)
break;
}
}
private static bool loopVariable = false;
void notifyIcon_BalloonTipClicked(object sender, EventArgs e)
{
loopVariable = true;
}
If you find yourself using doevents, you're likely doing something wrong. If you needed to run a loop like that use do {} rather than for (;;). In any case, you don't need either of those things. If this isn't supposed to run infinitely, you can disable the timer just before calling Application.SetSuspendState.
void Main()
{
Timer timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = 30000; //How often you want to show the tooltip?
timer.Enabled = true;
}
void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
{
Application.SetSuspendState(PowerState.Suspend, false, false);
}
void timer_Tick(object sender, EventArgs e)
{
notifyIcon1.ShowBalloonTip(10000);
}

Timer is firing before the elapsed Interval

I'm trying to create a Windows Form application that searches for a string and has three possible scenarios:
String 1 found - wait
String 2 found - stop
Else - Perform action and wait 1 minute
I am encountering my problem only on the times when it is expected to wait. When this happens, the newTimer_Tick starts to tick every second. I have tried disabling the timer when it ticks and a few other things but none appeared to work. Below is the code:
public void Action(string result)
{
if (result.Contains("string1"))
{
// Check again in 10 + x seconds
int n = new Random().Next(0, 5000);
int newtime = 10000 + n;
newTimer.Tick += new EventHandler(newTimer_Tick);
newTimer.Interval = newtime;
newTimer.Enabled = true;
}
else if (result.Contains("string2"))
{
// Turn off
newTimer.Enabled = false;
}
else
{
// Perform action and tick again in 1min + x seconds
action1();
int n = new Random().Next(0, 5000);
int newtime = 600000 + n;
newTimer.Tick += new EventHandler(newTimer_Tick);
newTimer.Interval = newtime;
newTimer.Enabled = true;
}
}
private void newTimer_Tick(object sender, EventArgs e)
{
Action( result );
}
What have I done wrong?
Each time the following line is called, an new instance of the event handler newTimerTick is added to the invocation list for the Tick event:
newTimer.Tick += new System.EventHandler(newTimer_Tick);
So every time the time tick goes off newTimerTick is going to be called multiple times, which is going to give you unexpected results.
Configure your event handler once only. In the constructor would be a sensible place.
Have you tried to stop the timer with the Timer.Stop method?
Btw: I don't think you need to reassign the Tick event from the newTimer unless you don't create a new Timer everytime.
I think what you were missing is that you have to stop your timer since you don't actually want it to keep for more than one interval. You seem to want to run it once, check on the result and then decide if you want to keep running it or not. Here's the code:
public void action(string result)
{
int n = new Random().Next(0, 5000);
Boolean blActivateTimer = true;
Timer timer = new Timer();
timer.Tick += timer_Tick;
if (!result.Contains("string1") && !result.Contains("string2"))
{
n += 600000;
action1();
}
else
{
if (result.Contains("string1"))
{
n += 10000;
}
else
{
blActivateTimer = false;
}
}
if (blActivateTimer)
{
timer.Start();
}
}
void action1()
{
}
void timer_Tick(object sender, EventArgs e)
{
Timer t = (Timer)sender;
t.Stop();
action(result);
}

Categories