I need to do some stuff in my application while application is running. I put it in dispatcher to work withing given time intervals. But now I want to randomized things.
I want to set random time intervals.
dTSettings.Tick += new EventHandler(dTSettings_Tick);
dTSettings.Interval = new TimeSpan(0, SetRandomTimer(), 0);
dTSettings.Start();
how to do that?
private DispatcherTimer _timer = new DispatcherTimer();
private Random rand = new Random();
public void InitAndStartTimer()
{
_timer.Tick += dispatcherTimer_Tick;
_timer.Interval = TimeSpan.FromSeconds(rand.Next(1, 10)); // From 1 s to 10 s
_timer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
_timer.Interval = TimeSpan.FromSeconds(rand.Next(1, 10)); // From 1 s to 10 s
// Do your work.
}
Related
I'm implementing a countdown in my app
private async void Window_Activated(object sender, WindowActivatedEventArgs args)
{
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += dispatcherTimer_Tick;
dispatcherTimer.Interval = new TimeSpan(0,1,0);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, object e)
{
TimeSpan timeSpan = new TimeSpan(blockTime.Hours, blockTime.Minutes, blockTime.Seconds);
if (timeSpan != TimeSpan.Zero)
{
timeSpan = timeSpan.Subtract(TimeSpan.FromMinutes(1));
Countdown_TexBlock.Text = String.Format("{0}:{1}", timeSpan.Hours, timeSpan.Minutes);
dispatcherTimer.Start();
}
else
{
dispatcherTimer.Stop();
}
}
The code works but only one time
For example I put 15 minutes in the blocktime (the time that the countdown will be running)
after a minute the countdown.text would be 0:14.
So only works after the first minute
Is not supposed to be restarted with dispatcher.start()
In the code that you posted, I don't see the blockTime variable being changed to any other value than it has in the beginning. This means that on every tick of dispatchTimer the value of the timeSpan.Subtract expression will always evaluate to the same 14 minutes. In your code, that 14 minutes is assigned to a local vaiable that is disposed when the tick is over. This gives the appearance that the dispatchTimer has stopped issuing Tick when it hasn't.
Here's what I ran that works as expected (for testing, I changed the minutes to seconds to make it observable in a reasonable time).
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
// Create the dispatch timer ONCE
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += DispatcherTimer_Tick;
dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
// This will restart the timer every
// time the window is activated
this.Activated += (sender, e) =>
{
startOrRestartDispatchTimer();
};
}
private void startOrRestartDispatchTimer()
{
dispatcherTimer.Stop(); // If already running
blockTime = TimeSpan.FromSeconds(15);
Countdown_TexBlock.Text = blockTime.ToString();
dispatcherTimer.Start();
}
private void DispatcherTimer_Tick(object sender, object e)
{
if (blockTime > TimeSpan.Zero)
{
blockTime = blockTime.Subtract(TimeSpan.FromSeconds(1));
Countdown_TexBlock.Text = blockTime.ToString();
if (blockTime == TimeSpan.Zero)
{
Countdown_TexBlock.Text = "Done";
dispatcherTimer.Stop();
}
}
}
TimeSpan blockTime = TimeSpan.FromSeconds(15);
private DispatcherTimer dispatcherTimer;
// This will restart the timer when the button is clicked.
private void buttonRestart_Click(object sender, RoutedEventArgs e) =>
startOrRestartDispatchTimer();
}
I have the following timer implementation. But the timer is not running every 5 seconds as needed. How can make this run every 5 seconds. At present its running about once in 30 seconds.
private void button1_Click(object sender, RoutedEventArgs e)
{
msgsent = 0;
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(0, 0, 5);
bool isenable = timer.IsEnabled;
timer.Start();
}
private async void timer_Tick(object sender, object e)
{
if (geo == null)
{
geo = new Geolocator();
}
Geoposition posi = await geo.GetGeopositionAsync();
if (posi.Coordinate.Point.Position.Latitude <= 12.9227 && posi.Coordinate.Point.Position.Longitude >= 080.1320)
{
if (msgsent <=1)
{
msgsent = msgsent + 1;
ShowDialog(new MessageDialog("Your Bus has crossed xyz"));
}
}
}
I'll give you a hint. If you understand where each goes, then it should be clear. If not, you will once you get better.
// in the class definition
int msgsent;
Timer timer;
and
// in the constructor
timer = new Timer();
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(0, 0, 5);
and
// in the Button.Click event handler
timer.Start();
and
// in the Timer.Tick event handler
timer.Stop();
/* do your work here */
timer.Start();
There will be further issues when the user is clicking the button while you're doing your work, but that's beyond the scope of this question.
I am trying to make a program with 2 timers in it running at different intervals. Currently I have 1 timer working fine and I need to have another one running. My code for the first timer that works looks like this:
private void startButton_Click(object sender, RoutedEventArgs e)
{
Random rand = new Random();
int ranMin = rand.Next(1,24);
int ranSec = rand.Next(0, 59);
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, ranMin, ranSec);
dispatcherTimer.Start();
min.Content = ranMin;
sec.Content = ranSec;
openP();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
**code for timer in here
}
This works fine, but now I need another timer running at a 1second interval with different code and when I try to duplicate this by just making all the dispatcherTimer into dispatcherTimer2 I am running into errors.
I am not sure what you were doing (you should post the error), but the following works with your supplied code:
private void startButton_Click(object sender, RoutedEventArgs e)
{
Random rand = new Random();
int ranMin = rand.Next(1,24);
int ranSec = rand.Next(0, 59);
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, ranMin, ranSec);
dispatcherTimer.Start();
// New timer
System.Windows.Threading.DispatcherTimer dispatcherTimer2 = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer2.Tick += new EventHandler(dispatcherTimer2_Tick);
dispatcherTimer2.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer2.Start();
min.Content = ranMin;
sec.Content = ranSec;
openP();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
//code for timer in here
}
private void dispatcherTimer2_Tick(object sender, EventArgs e)
{
//code for timer2 in here
}
what i want to do is pause a video after every 10s
the video should pause after ever 10s till the video ends
the code given below gives unexpected results
the video pauses fine for the firs time (i.e after 10s)
but when i play again it should pause after 10s but in my case it pauses randomly sometimes at 8s,3s 5s and etc
what should i do??
please help
thanks!!
void PlayClick(object sender, EventArgs e)
{
VideoControl.Play();
var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
VideoControl.Pause();
}
Add this in your dispatcherTimer_Tick-Method:
dispatcherTimer.Stop();
Move the following part into the constructor:
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
Make the DispatcherTimer a global variable.
EDIT: Thats how it should look like:
class MyClass
{
private DispatcherTimer _dispatcherTimer; //now your dispatcherTimer is accessible everywhere in this class
public MyClass()
{
_dispatcherTimer = new DispatcherTimer();
_dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
_dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
}
void PlayClick(object sender, EventArgs e)
{
VideoControl.Play();
_dispatcherTimer.Start();
}
void dispatcherTimer_Tick(object Sender, EventArgs e)
{
_dispatcherTimer.Stop();
VideoControl.Pause();
}
}
Bring the declaration of the timer out into a private class variable, move a couple lines to the constructor of the class, and stop the timer in the Tick handler.
The reason you don't want to keep creating the timer is because there are unmanaged resources involved with a timer and so you're closing that loop.
private dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
ctor
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
}
void PlayClick(object sender, EventArgs e)
{
VideoControl.Play();
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
dispatchTimer.Stop();
VideoControl.Pause();
}
Try with following code in Tick event:
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
(sender as DispatcherTimer).Stop();
VideoControl.Pause();
}
You can make dispatcherTimer object outside Playclick event and only put Start() method inside PlayClick event in following way:
var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
public Form1() //// form constructor where you are handling these all event....
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
}
void PlayClick(object sender, EventArgs e)
{
VideoControl.Play();
dispatcherTimer .Start();
}
I have a wpf application(No MVVM), this application requires several background thread(Runs with specific time interval).
These thread should be on Application Level i.e. if user is on any WPF Window, these threads should be active.
Basically these thread will are using external resources so locking is also required.
Kindly tell me the best way to do this.
If you want to execute an action periodically in a WPF application you can use the DispatcherTimer class.
Put your code as the handler of the Tick event and set the Interval property to whatever you need. Something like:
DispatcherTimer dt = new DispatcherTimer();
dt.Tick += new EventHandler(timer_Tick);
dt.Interval = new TimeSpan(1, 0, 0); // execute every hour
dt.Start();
// Tick handler
private void timer_Tick(object sender, EventArgs e)
{
// code to execute periodically
}
private void InitializeDatabaseConnectionCheckTimer()
{
DispatcherTimer _timerNet = new DispatcherTimer();
_timerNet.Tick += new EventHandler(DatabaseConectionCheckTimer_Tick);
_timerNet.Interval = new TimeSpan(_batchScheduleInterval);
_timerNet.Start();
}
private void InitializeApplicationSyncTimer()
{
DispatcherTimer _timer = new DispatcherTimer();
_timer.Tick += new EventHandler(AppSyncTimer_Tick);
_timer.Interval = new TimeSpan(_batchScheduleInterval);
_timer.Start();
}
private void IntializeImageSyncTimer()
{
DispatcherTimer _imageTimer = new DispatcherTimer();
_imageTimer.Tick += delegate
{
lock (this)
{
ImagesSync.SyncImages();
}
};
_imageTimer.Interval = new TimeSpan(_batchScheduleInterval);
_imageTimer.Start();
}
These three threads a intialized on App_OnStart
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
try
{
_batchScheduleInterval = Convert.ToInt32(ApplicationConfigurationManager.Properties["BatchScheduleInterval"]);
}
catch(InvalidCastException err)
{
TextLogger.Log(err.Message);
}
Helper.SaveKioskApplicationStatusLog(Constant.APP_START);
if (SessionManager.Instance.DriverId == null && _batchScheduleInterval!=0)
{
InitializeApplicationSyncTimer();
InitializeDatabaseConnectionCheckTimer();
IntializeImageSyncTimer();
}
}