In my application I have a System.Timers.Timer which fires a second time a few milliseconds later.
Declaration of the timer:
mRecipeTimer = new System.Timers.Timer(30000);
mRecipeTimer.Start();
mRecipeTimer.Elapsed += new ElapsedEventHandler(mRecipeTimer_Elapsed);
Timer elapse event:
void mRecipeTimer_Elapsed(object sender, ElapsedEventArgs e)
{
int sync = Interlocked.CompareExchange(ref syncPoint, 1, 0);
if (sync == 0)
{
Thread.CurrentThread.Name = string.Format("timer, started at {0} ({1})", DateTime.Now, DateTime.Now.Millisecond);
Log.Info("Recipe timer elapsed.");
// some code
syncPoint = 0;
}
}
And this is what I see in my logs:
2012-01-31 11:17:26,797 [timer, started at 1/31/2012 11:17:26 AM (797)] INFO - Recipe timer elapsed.
2012-01-31 11:17:27,875 [timer, started at 1/31/2012 11:17:27 AM (875)] INFO - Recipe timer elapsed.
2012-01-31 11:17:56,797 [timer, started at 1/31/2012 11:17:56 AM (797)] INFO - Recipe timer elapsed.
2012-01-31 11:17:57,875 [timer, started at 1/31/2012 11:17:57 AM (875)] INFO - Recipe timer elapsed.
I allready placed an interlock so that only one action may run at the same time. But unfornately the timer fires its event twice and I don't know why.
You can always disable/enable the timer while the event is being processed, i.e.,
void mRecipeTimer_Elapsed(object sender, ElapsedEventArgs e)
{
mRecipeTimer.Enabled = false; //<---- disable
int sync = Interlocked.CompareExchange(ref syncPoint, 1, 0);
if (sync == 0)
{
Thread.CurrentThread.Name = string.Format("timer, started at {0} ({1})", DateTime.Now, DateTime.Now.Millisecond);
Log.Info("Recipe timer elapsed.");
// some code
syncPoint = 0;
}
mRecipeTimer.Enabled = true; //<---- enable
}
Related
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.
bool elapsed = false;
private void timerElapsed(object sender, System.Timers.ElapsedEventArgs e)
{
elapsed = true;
}
private void WorkerThreadFunction()
{
Timer _timer = new System.Timers.Timer(60000);
_timer.Elapsed += timerElapsed;
_timer.AutoReset = false;
while (!elapsed)
{
// Do something...
Thread.Sleep(50);
}
}
How is the global variable "elapsed" reacting? Is it possible to run more separate WorkerThreads with timers?
Of course it is possible to run more separate WorkerThreads. Each one will have it's own timer. There shouldn't be a problem.
The variable bool elapsed will be set to true by the first Thread that finishes its job, and it will stay true until some other process sets it to false. If you are unlucky some thread might even not start its job because the first on has set your elapsed to true
EDIT:
it seems that your thread job is encapsulated.
So you could actually also just use a stopwatch, if you don't need to access global variables from within the thread
private void WorkerThreadFunction()
{
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
while(watch.ElapsedMilliseconds < 60000)
{
// Do something...
Thread.Sleep(50);
}
watch.Stop();
}
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
My program has a parameter that starts up the winform and waits x number of seconds before it runs a function. Currently I am using Thread Sleep for x seconds and then the function runs. how can I add a timer in the strip status label?
so that it says: x Seconds Remaining...
Instead of blocking thread execution, simply call your method when required timeout passes. Place new Timer to your form, and set it's Interval to 1000. Then subscribe to timer's Tick event and calculate elapsed time in event handler:
private int secondsToWait = 42;
private DateTime startTime;
private void button_Click(object sender, EventArgs e)
{
timer.Start(); // start timer (you can do it on form load, if you need)
startTime = DateTime.Now; // and remember start time
}
private void timer_Tick(object sender, EventArgs e)
{
int elapsedSeconds = (int)(DateTime.Now - startTime).TotalSeconds;
int remainingSeconds = secondsToWait - elapsedSeconds;
if (remainingSeconds <= 0)
{
// run your function
timer.Stop();
}
toolStripStatusLabel.Text =
String.Format("{0} seconds remaining...", remainingSeconds);
}
You can use a Timer:
public class Form1 : Form {
public Form1(){
InitializeComponent();
t = new Timer {Interval = 1000};
t.Tick += Tick;
//try counting down the time
CountDown(100);
}
DateTime start;
Timer t;
long s;
public void CountDown(long seconds){
start = DateTime.Now;
s = seconds;
t.Start();
}
private void Tick(object sender, EventArgs e){
long remainingSeconds = s - (DateTime.Now - start).TotalSeconds;
if(remainingSeconds <= 0) {
t.Stop();
toolStripStatusLabel1.Text = "Done!";
return;
}
toolStripStatusLabel1.Text = string.Format("{0} seconds remaining...", remainingSeconds);
}
}
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);
}