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...
}
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
I have a textbox, I have using both Timer and DispatcherTimer for delay on keyup, but it not actually as my expected.
Event stil fire when Interval is finish. After 5 seconds, the Fiter event stil fire.
Here are my code:
Init variable
DispatcherTimer timerFilter;
//or
//Timer timerFilter = new Timer(5000);
Init event
InitializeComponent();
timerFiter = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timerFiter.Tick += (s, args) =>
{
Filter();
};
//or
//timerFilter.Elapsed += Filter;
When key up
Console.WriteLine("Start");
timerFilter.Start();
//or
//timerFilter.Enabled = true;
When key down
Console.WriteLine("Destroy");
timerFiter.Stop();
//or
//timerFilter.Enabled = false;
My event
private void Filter(Object source, ElapsedEventArgs e)
{
Console.WriteLine("Filter");
timerFiter.Stop();
//or
//timerFilter.Enabled = false;
}
Thanks!
There is always a key up event, so the last thing that will happen after the last key press is:
Console.WriteLine("Start");
timerFilter.Start();
To make sure that your timer stops after the results are filtered, add a Stop call to your Filter handler:
private void Filter(Object source, ElapsedEventArgs e)
{
Console.WriteLine("Filter");
timerFilter.Stop();
}
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();
}
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);
}
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