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
Related
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...
}
I want my timer to continue from the time I started it until now, I need help with the logic that uses timespan to calculate the elapsed time from the minutes the timer started to the current time, Here is what I have done:
CancellationTokenSource cts = _cancellationTokenSource; // safe copy
//Timer Starts here
_TimeSpan = TimeSpan.FromMinutes(TimeSheet.TotalTime);
//Increment timer by a second interval
Device.StartTimer(TimeSpan.FromSeconds(1), () => {
if (cts.IsCancellationRequested)
{
return false;
}
else
{
Device.BeginInvokeOnMainThread(() => {
_TimeSpan += TimeSpan.FromSeconds(1);
displaytime = _TimeSpan.ToString(#"h\:m\:s");
TimeSheet.TotalTimeForDisplay = displaytime;
Console.WriteLine("Timer");
Console.WriteLine(displaytime);
});
return true;
}
use System.Timers.Timer
// use whatever start time you need
DateTime start = DateTime.Now;
// 1000ms = 1s
System.Timers.Timer timer = new System.Timers.Timer(1000);
timer.Elapsed += OnTimedEvent;
timer.Start();
then
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
var elapsed = DateTime.Now - start;
}
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
}
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