Offset Timer starts - c#

Hi new to the site so I apologize if my question is not properly formatted
If i have two events that need to alternate every 2 seconds (one is ON the other is OFF), how can i delay the start of one of the timers for the 2 second offset?
static void Main(string[] args)
{
Timer aTimer = new Timer();
Timer bTimer = new Timer();
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
bTimer.Elapsed += new ElapsedEventHandler(OnTimedEventb);
// Set the Interval to 4 seconds
aTimer.Interval = 4000;
aTimer.Enabled = true;
bTimer.Interval = 4000;
bTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The status is on {0}", e.SignalTime);
}
private static void OnTimedEventb(object source, ElapsedEventArgs b)
{
Console.WriteLine("The state is off {0}", b.SignalTime);
}
So I basically want the ON event to happen when the program starts, then 2 seconds later have the OFF event fire and so on
using vs 2012 console app but I will be using in windows forms program

You can create a class level bool called IsOn, for example, and toggle that. You only need one timer to do this as true would mean it's on and false would mean it's off.
private static bool IsOn = true; //default to true (is on)
static void Main(string[] args)
{
Timer aTimer = new Timer();
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds
aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
IsOn = !IsOn;
Console.WriteLine("The status is {0} {1}", IsOn.ToString(), e.SignalTime);
}

Related

A method was called at an unexpected time, when running a timer

I have the following issue, I'm running the timer (SetTimer), and it is supposed to, on elapsed, run the next function (OnTimedEvent).
However, when it is supposed to run, it fails with "A method was called at an unexpected time" error on the "CoreDispatch".
I have tried searching for a solution, and I think I understand what is causing it, but I'm not sure how to fix it.
Hopefully some of you can shed some light on my issue.
private void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(RandomNum(1000,2000));
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
public async void OnTimedEvent(Object source, ElapsedEventArgs e)
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
System.Diagnostics.Debug.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
}
);
}
Call DispatcherQueue.GetForCurrentThread on the UI thread to get a DispatcherQueue and then use it to enqueue dispatcher work:
readonly DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread();
private void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(RandomNum(1000,2000));
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
public void OnTimedEvent(Object source, ElapsedEventArgs e)
{
dispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
{
System.Diagnostics.Debug.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
});
}
Or use a DispatcherTimer:
DispatcherTimer aTimer;
private void SetTimer()
{
aTimer = new DispatcherTimer();
aTimer.Interval = TimeSpan.FromMilliseconds(RandomNum(1000,2000));
aTimer.Tick += ATimer_Tick;
aTimer.Start();
}
private void ATimer_Tick(object sender, object e)
{
// do something on the UI thread...
}

Set Time Interval in Timer in Xamarin

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

I need to create a timer based application?

I need to create a application which must have a timer control;
the timer must automatically initialize when each form is called, when the time reach 3 seconds means it must load the another form.
I have tried this:
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
if (timer1.Interval = 3000)
{
MessageBox.Show("Times up");
form2 i=new form2();
form2.show();
}
}
but I cant get the correct result....
Timers in C# work by firing events periodically. You need to attach an event handler which responds to the timer event. The MSDN documentation has a straightforward example (code snippet reproduced below).
public Timer aTimer;
public static void Main()
{
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
initialize and enable your timer and attach an event handler to Tick event.
Timer timer;
private void Form1_Load(object sender, EventArgs e)
{
timer = new Timer();
timer.Enabled = true;
timer.Interval = 3000;
timer.Tick += timer_Tick;
timer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("Times up");
Form2 i = new Form2();
i.Show();
}

C# Timer - Need help disabling timer until code executes then restart timer. Currently maxing CPU :(

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

Unstoppable Timer

I'm attempting to make a "simple" timer from 15 minutes to 0 seconds. I'm using 900 seconds as my 15 minutes. When I Run the program it runs through fine but Continues going into the negatives. I'm still a novice at C#. I'm wanting the code to stop at 0 and run an alert to grab someone's attention. Here is what I have thus far
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
namespace GBS_GI_Timer
{
public class Program
{
public static int t = 2;
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 1000;
aTimer.Enabled = true;
//Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
//GC.KeepAlive(aTimer);
if (t == 0)
aTimer.Stop();
}
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
//TimeSpan timeRemaining = TimeSpan.FromSeconds(t);
Console.WriteLine("Time remianing..{0}", t);
t--;
if (t == 0)
{
Console.WriteLine("\a");
Console.WriteLine("Time to check their vitals, again!");
Console.WriteLine("Press any key to exit...");
}
// Console.ReadKey();
Console.ReadLine();
}
}
}
You have it coded so that when you hit enter (or type something and hit enter), it then checks t and may stop the timer. You're checking if t == 0 and only then stopping the timer. What happens if t is less than zero before you hit enter?
You would have to refactor your code as below to make it work, System.Timers.Timer used ThreadPool to run the callback routines.
class Program
{
public static int t = 2;
static System.Timers.Timer aTimer = new System.Timers.Timer();
public static void Main()
{
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 1000;
aTimer.Enabled = true;
Console.ReadLine();
}
public static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Time remianing..{0}", t);
t--;
if (t == 0)
{
Console.WriteLine("\a");
Console.WriteLine("Time to check their vitals, again!");
Console.WriteLine("Press any key to exit...");
aTimer.Stop();
Console.ReadLine();
}
}
}
There are some other logic issues with your program as it stands, and I am not certain it would do what you want even if it was running, though.
I would refactor your OnTimedEvent to just do
Console.WriteLine(string.Format("{0} time to check their vitals!"));
and use a while loop to check the status of t in the main routine.
You could also change the Timer.Interval when entering the handler so that no other events fire until they acknowledge the first event, but then you couldn't guarantee that this routine runs for 15 minutes...

Categories

Resources