Call method after certain random interval of time - c#

I have 5 methods and I need them to be called after random interval(1 to 3 sec) of time. Say first method is called after 1 sec, then second method is called after 2.3 sec, next method after 1.5 etc. I did following using timer
System.Windows.Forms.Timer mytimer = new System.Windows.Forms.Timer();
mytimer.Tick += new EventHandler(TimerEventProcessor);
Random rand = new Random();
int fortimerinterval = rand.Next(1000, 3000);
mytimer.Interval = fortimerinterval;
mytimer.Enabled = true;
mytimer.Start();
public void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
fortimerinterval = rand.Next(1000, 3000);
mytimer.Interval = fortimerinterval;
first time call function1, then call function2
//this is main theme, so im not giving whole code here
}
But timer interval remain unchanged after it gets first random value. It seems that, timerinterval value don't change for each time TimerEventProcessor is called. How can I do that? Or if there is any other easy way to do this. Thanks

I've modified your code a bit and tried it. It works allright.
Random rand = new Random();
Timer mytimer = new Timer();
private void fireTimerClick(object sender, EventArgs e)
{
mytimer.Tick += new EventHandler(TimerEventProcessor);
mytimer.Interval = rand.Next(1000, 3000);
mytimer.Enabled = true;
mytimer.Start();
}
public void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
mytimer.Interval = rand.Next(1000, 3000);
System.Diagnostics.Debug.WriteLine(DateTime.Now);
}
You can verify this with the debug output window. fireTimerClick is simply a button click event handler.

Related

Using timer in windows form application

I am new to coding and are having trouble.
I want to use a timer that will start upon pressing ScatterMode tab, it will start counting 4sec before running "Dosomething" function. This cycle will repeat itself until i decide to stop the program. But the problem i get is, this code only run correctly for like 2loop, after that the timer sort of go crazy LOL.
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
//ScatterMode Tab
private void Scatter_modeToolStripMenuItem_Click(object sender, EventArgs e)
{
timer.Interval = 4000;
timer.Enabled = true;
timer.Tick += new EventHandler(Dosomething);
timer.Start();
}
private void Dosomething (object sender, EventArgs e)
{
timer.Stop();
timer.Enabled = false;
Grab.buffer(out buffer, out status, 6000);
Scatter_mode(buffer);
pictureBox1.Refresh();
int done_grab = 1;
if (doneGrab == 1)
{
timer.Interval = 4000;
timer.Enabled = true;
timer.Tick += new EventHandler(Scatter_modeToolStripMenuItem_Click);
timer.Start();
done_grab = 0;
}
}
Adding a new event handler to a timer, to handle its tick event, inside the handler for the tick event will indeed cause the timer to go "crazy". Every time the timer raises its event, another event handler (that responds to events raised) will be added. This means the next time the timer ticks, the event code will run twice. Two new event handlers will be added. Next time the timer ticks, the code will run 4 times. 4 event handlers will be added ... and so on
Remove this line from your code:
timer.Tick += new EventHandler(Scatter_modeToolStripMenuItem_Click);
And move this line into your form's constructor:
timer.Tick += new EventHandler(Dosomething);
You only want to wire this event handler up once. Every time the timer's interval elapses, the code will run, once :)
I'll also do a bit of a peer review of your code, see the comments:
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
//ScatterMode Tab
private void Scatter_modeToolStripMenuItem_Click(object sender, EventArgs e)
{
timer.Interval = 4000; //can go in the constructor also; don't need to set repeatedly
timer.Enabled = true;
timer.Tick += new EventHandler(Dosomething); //move to constructor
timer.Start(); //this isn't needed - you already Enabled the timer, which started it
}
private void Dosomething (object sender, EventArgs e)
{
timer.Stop(); //use this
timer.Enabled = false; //or this. It's not required to do both
Grab.buffer(out buffer, out status, 6000); //if these lines crash then your timer will
Scatter_mode(buffer); //only restart if the toolstripmenuitemclick
pictureBox1.Refresh(); //above runs.. is it what you wanted?
int done_grab = 1; //not needed
if (doneGrab == 1) //this will always evaluate to true, it is not needed
{
timer.Interval = 4000; //the interval is already 4000, not needed
timer.Enabled = true; //careful; your timer may stop forever if the code above crashes
timer.Tick += new EventHandler(Scatter_modeToolStripMenuItem_Click); //remove
timer.Start(); //not needed
done_grab = 0; //not needed
}
}

C# timer I can speed up but not slow down

I have a timer event setup and I would like to change how often the timer event happens by reading a number from a text box. If the box is '10' and you click the update button the event would trigger every 10ms then if you changed to '100' and clicked it would happen every 100ms and so on.
When I run the program however, i can speed up the event frequency (e.g. 100ms to 10ms) but I cannot slow it down (e.g. 10ms to 100ms). Here is the piece of my code that changes the timer when I click:
private void TimerButton_Click(object sender, EventArgs e)
{
getTime = ImgTimeInterval.Text;
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = false;
timer.Interval = timerMS;
timer.Elapsed += new ElapsedEventHandler(timerEvent);
timer.AutoReset = true;
timer.Enabled = true;
}
}
public void timerEvent(object source, System.Timers.ElapsedEventArgs e)
{
label1.Text = counter.ToString();
counter = (counter + 1) % 100;
}
If anyone knows what I may be doing wrong it would be greatly appreciated.
The problem with this code is, that you create a new Timer each time you click the button. Try to create the timer outside the method. You think it's only goes faster, but instead multiple timers trigger the timerEvent
private System.Timers.Timer _timer;
private void CreateTimer()
{
_timer = new System.Timers.Timer();
_timer.Enabled = false;
_timer.Interval = 100; // default
_timer.Elapsed += new ElapsedEventHandler(timerEvent);
_timer.AutoReset = true;
_timer.Enabled = true;
}
private void TimerButton_Click(object sender, EventArgs e)
{
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
_timer.Interval = timerMS;
}
}
public void timerEvent(object source, System.Timers.ElapsedEventArgs e)
{
label1.Text = counter.ToString();
counter = (counter + 1) % 100;
}
Make sure that the CreateTimer is called in the constructor/formload. Also you can now stop the timer within another button event. With _timer.Enabled = false;
You're always creating a new timer and never stopping the old timer. When you "change" it from 100 to 10 your 100ms timer is still firing every 100 ms, so every 100ms two timers are firing at around the same time.
You need to "remember" the old timer so that you can stop it. Or, better yet, just have only one timer that you change the interval on.
private System.Timers.Timer timer = new System.Timers.Timer();
public Form1()
{
timer.Enabled = false;
timer.AutoReset = true;
timer.Elapsed += timerEvent;
}
private void TimerButton_Click(object sender, EventArgs e)
{
getTime = ImgTimeInterval.Text;
bool isNumeric = int.TryParse(ImgTimeInterval.Text, out timerMS); //if number place number in timerMS
label2.Text = isNumeric.ToString();
if (isNumeric)
{
timer.Interval = timerMS;
timer.Enabled = true;
}
}
Well the basic problem is that you're building a new one every time. Make a private timer:
private System.Timers.Timer _timer = new System.Timers.Timer();
and then fix it up when the button is clicked:
if (isNumeric)
{
_timer.Stop();
_timer.Interval = timerMS;
_timer.Start();
}
and then in the .ctor, do this:
_timer.Elapsed += new ElapsedEventHandler(timerEvent);
Now you have a single timer that you are just modifying as the user changes the value in the text box.

Call method after random interval of time

I have 5 methods and I need them to be called after random interval(1 to 3 sec) of time. Say first method is called after 1 sec, then second method is called after 2.3 sec, next method after 1.5 etc. I did following using timer
Random rand = new Random();
fortimerinterval1 = rand.Next(1000, 3000);
mytimer1.Interval = fortimerinterval1;
mytimer1.Enabled = true;
mytimer1.Start();
But the problem is, timer interval do not change everytime. Timer interval remain constant after first time. How to make it random so that each time timer interval change.
Do something like this
Random rand = new Random();
Timer mytimer = new Timer();
private void button1_Click(object sender, EventArgs e)
{
mytimer.Tick += new EventHandler(TimerEventProcessor);
int fortimerinterval = rand.Next(1000, 3000);
mytimer.Interval = fortimerinterval;
mytimer.Enabled = true;
mytimer.Start();
}
public void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
int fortimerinterval = rand.Next(1000, 3000);
mytimer.Interval = fortimerinterval;
System.Diagnostics.Debug.WriteLine(DateTime.Now);
}
Set the interval in your timer elapsed method.
Random rand = new Random();
private void OnTick(object sender, EventArgs eventArgs)
{
_timer.Interval = rand.Next(1000, 3000);
}
Watch out for overlapped callbacks if you use System.Timers.Timer. For example, if the first tick fires after 1 second and the method that you call in the tick callback takes longer than 1 second to complete, you'll end up with another tick callback being called 1 second after the first, before you change the interval.
I would use a System.Threading.Timer configured to fire once and in the callback method change it to fire again at the next random interval.
Like this:
public TestClass()
{
_random = new Random(Environment.TickCount);
_timer = new Timer(TimerCallback, null, _random.Next(1000, 3000), Timeout.Infinite);
}
private void TimerCallback(object state)
{
try
{
// Do something.
}
finally
{
_timer.Change(_random.Next(1000, 3000), Timeout.Infinite);
}
}

Getting time until next event

I have a sync timer in my app that fires up a function at a given time... now I want to know how much time is left until the next call to that function.
This is my call to the timer:
var syncTime = time.activitylog;
double time = TimeSpan.Parse(syncTime).TotalMilliseconds;
System.Timers.Timer myTimer = new System.Timers.Timer();
myTimer.Elapsed += new ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = time;
myTimer.Start();
How do I get the time until next call?
Thanks
You can use another timer, and set the Interval of that the value that you want,exactly a part time of the Interval of original timer.
Then start them Simultaneously,I mean at the same time.
UPDATE :
Maybe this code describes my solution better :
public Form1()
{
InitializeComponent();
}
System.Windows.Forms.Timer trOriginal = new System.Windows.Forms.Timer();
System.Windows.Forms.Timer trRemain = new System.Windows.Forms.Timer();
double remain = 0;
private void button1_Click(object sender, EventArgs e)
{
trOriginal.Interval = 1000;
trRemain.Interval = 1;
trOriginal.Tick += new EventHandler(trOriginal_Tick);
trRemain.Tick += new EventHandler(trRemain_Tick);
trOriginal.Start();
trRemain.Start();
}
void trRemain_Tick(object sender, EventArgs e)
{
remain -= trRemain.Interval;
Console.WriteLine("remain MS to next event : " + remain);
}
void trOriginal_Tick(object sender, EventArgs e)
{
remain = trOriginal.Interval;
}
You can use a System.Diagnostics.Stopwatch to keep track of how much time has passed already and restart the Stopwatch with every tick of your Timer.
Stopwatch watch = new Stopwatch();
private void DisplayTimeEvent(object sender, EventArgs e)
{
watch.Restart();
// Whatever is supposed to happen, when the timer ticks
}
Now whenever you want to know how much time is left until the event is fired next, you can do this:
long timeLeft = myTimer.Interval - watch.ElapsedMilliseconds;

C# Timer - Need help disabling timer until code executes then restart timer. Currently maxing CPU :(

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

Categories

Resources