Do the action after a certain amount of time, but if called manually, reset the timer
I use System.Timers.Timer
to execute an action every 10 seconds. This action can also be called by other methods if a special condition occurs or through an interface. If the action is not being called from the timer, I just reset the timer.
The code I'm using ...
timer = new Timer();
timer.Elapsed += (sender, args) => ExecuteAction();
timer.Interval = 10000;
timer.Enabled = true;
public void ExecuteActionAndResetTimer()
{
ExecuteAction();
timer.Stop();
timer.Start();
}
private void ExecuteAction()
{
// do the work...
}
Expected result if "X" is the action called by the timer (i.e. ExecuteAction
), " X " is the action called from the external timer (i.e. ExecuteActionAndResetTimer
), and "o" is the second:
XooooXo X about X ooooXo X ooooX
This works great. I just want to know that we can do this with reactive extensions?
Thank.
source to share
Yes, this is pretty easy to do with Rx.
Here's how:
var subject = new Subject<char>();
var query =
subject
.StartWith('X')
.Select(c =>
Observable
.Interval(TimeSpan.FromSeconds(10.0))
.Select(n => 'X')
.StartWith(c))
.Switch();
query.Subscribe(x => Console.Write(x));
Thread.Sleep(5000);
subject.OnNext('Q');
Thread.Sleep(15000);
subject.OnNext('W');
This creates consistency XQXWXXXX
with the final X
running ad-infinitum.
source to share