DispatcherTimer apply interval and execute immediately - c#

Basically when we apply some interval ie 5 sec we have to wait for it.
Is it possible to apply interval and execute timer immediately and don't wait 5 sec?
(I mean the interval time).
Any clue?
Thanks!!
public partial class MainWindow : Window
{
DispatcherTimer timer = new DispatcherTimer();
public MainWindow()
{
InitializeComponent();
timer.Tick += new EventHandler(timer_Tick);
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("!!!");
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
}
}

There are definitely more elegant solutions, but a hacky way is to just call the timer_Tick method after you set the interval initially. That'd be better than setting the interval on every tick.

Initially set the interval to zero and then raise it on a subsequent call.
void timer_Tick(object sender, EventArgs e)
{
((Timer)sender).Interval = new TimeSpan(0, 0, 5);
MessageBox.Show("!!!");
}

could try this:
timer.Tick += Timer_Tick;
timer.Interval = 0;
timer.Start();
//...
public void Timer_Tick(object sender, EventArgs e)
{
if (timer.Interval == 0) {
timer.Stop();
timer.Interval = SOME_INTERVAL;
timer.Start();
return;
}
//your timer action code here
}
Another way could be to use two event handlers (to avoid checking an "if" at every tick):
timer.Tick += Timer_TickInit;
timer.Interval = 0;
timer.Start();
//...
public void Timer_TickInit(object sender, EventArgs e)
{
timer.Stop();
timer.Interval = SOME_INTERVAL;
timer.Tick += Timer_Tick();
timer.Start();
}
public void Timer_Tick(object sender, EventArgs e)
{
//your timer action code here
}
However the cleaner way is what was already suggested:
timer.Tick += Timer_Tick;
timer.Interval = SOME_INTERVAL;
SomeAction();
timer.Start();
//...
public void Timer_Tick(object sender, EventArgs e)
{
SomeAction();
}
public void SomeAction(){
//...
}

That's how I solved it:
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(DispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
dispatcherTimer.Start();
DispatcherTimer_Tick(dispatcherTimer, new EventArgs());
Works for me without any issues.

Disclaimer: This answer is not for the OP because he wants to use DispatcherTimer
But if you do not have this limitation and you can use another Timer, then there is a cleaner solution
You can use System.Threading.Timer
The most important thing is setting dueTime:0
System.Threading.Timer timer = new Timer(Callback, null, dueTime:0, period:10000);
The documentation of the dueTime is the following
The amount of time to delay before callback is invoked, in milliseconds. Specify Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately.
and your callback is like this
private void Callback(object? state) =>
{
}
Again this does not use DispatcherTimer but it could solve your problem
Related answer

Related

Timer gets faster on next calls wp8.1

i have a countdown timer like this:
private DispatcherTimer _timer;
private int _countdown;
private void initialize_timer()
{
_countdown = 100;
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromSeconds(1);
_timer.Tick += (s, e) => Tick();
_timer.Start();
}
private void Tick()
{
_countdown--;
if (_countdown == 0)
{
_timer.Stop();
}
TimeSpan time = TimeSpan.FromSeconds(_countdown);
string str = time.ToString(#"dd\:hh\:mm\:ss");
RemainingTime.Text = str;
}
it works fine until i call initialize_timer() again. the timer gets faster on every call. note that _countdown will be a dynamic value based on a future time so it will change on each call.
When you call initialize_timer(), you create a new Timer but your old Timer is still there and ticking. Just remove the lines
_timer = new DispatcherTimer();
_timer.Tick += (s, e) => Tick();
and you'll be OK.

My elapsed time is only going up to 60

How can I create a elapsed time method that goes beyond 60 seconds AND counts only in seconds. My current implementation constantly repeats every 60 seconds.
CODE:
void timer_Tick(object sender, EventArgs e)
{
time = DateTime.Now.Second.ToString();
//DateTime.Now.ToLongTimeString();
}
public void timeSetup()
{
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1);
//timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
}
No need to make things harder than necessary:
class TimerClass
{
public int time;
void timer_Tick(object sender, EventArgs e)
{
time++;
}
public void timeSetup()
{
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick += timer_Tick;
timer.Start();
}
}
This calls the Tick handler every second and counts the number of times it is called. This can be imprecise for measuring long periods of time. For the long run, use
time = (DateTime.Now - startTime).TotalSeconds;
where startTime is initialized as the time when you start the timer.

How to stop a Dispatcher when the event tick?

I need to stop the event connected to the Dispatcher after the event first time tick.
Any idea how to do it.
int closeSeconds = Convert.ToInt32(utility.GetConfiguration("device", "closePopupPrinterAfterSeconds"));
var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimerCheckPopupPrinter_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, closeSeconds);
dispatcherTimer.Start();
private void dispatcherTimerCheckPopupPrinter_Tick(object sender, EventArgs e)
{
// stop the dispatcherTimer here, so this method will not fire every x seconds
System.Windows.Threading.Dispatcher displatcher = (System.Windows.Threading.Dispatcher)sender;
}
Cast the sender argument to DispatcherTimer, not Dispatcher, and call its Stop method, or set its IsEnabled property to false.
private void dispatcherTimerCheckPopupPrinter_Tick(object sender, EventArgs e)
{
var timer = (DispatcherTimer)sender; // not Dispatcher!
timer.Stop(); // or timer.IsEnabled = false;
}

Timer for Windows Phone 8

I wish to execute a function at an interval of 1 or so minutes. How can I achieve this in Windows Phone 8. I am not looking for background agents. The app will be running in the foreground. What are my options?
you can use the DispatcherTimer Class
private DispatcherTimer dispatcherTimer;
// Constructor
public MainPage()
{
InitializeComponent();
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
//do whatever you want to do here
}
Refer: (http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer(v=vs.110).aspx)
Try this
public void Start_timer()
{
DispatcherTimer timer = new DispatcherTimer();
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(00, 0, 10);
bool enabled = timer.IsEnabled;
timer.Start();
}
void timer_Tick(object sender, object e)
{
//function to execute
}
You can also use ThreadPoolTimer:
TimeSpan period = TimeSpan.FromSeconds(60);
ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((source) =>
{
// TODO: Work
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// UI update
});
}, period);
One option may be to use DispatcherTimer.
Simply register a callback on the Tick event.

How do I create a timer in WPF?

I am a newbie in timer in wpf and I need a code that every 5mins there is a message box will pop up. .can anyone help me for the simple code of timer.
That's what I tried so far:
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
private void test()
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// code goes here
}
private void button1_Click(object sender, RoutedEventArgs e)
{
test();
}
In WPF, you use a DispatcherTimer.
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// code goes here
}
Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

Categories

Resources