Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a method after delay on time only

I'm using this method to call another method every 60 seconds:

Timer updateTimer = new Timer(testt, null, 
                              new TimeSpan(0, 0, 0, 0, 1), new TimeSpan(0, 0, 60));

It is possible to call this method only once after delay of 1 millisecond?

like image 343
YosiFZ Avatar asked Nov 29 '22 13:11

YosiFZ


2 Answers

Assuming this is a System.Threading.Timer, from the documentation for the constructor's final parameter:

period
The time interval between invocations of the methods referenced by callback. Specify negative one (-1) milliseconds to disable periodic signaling.

So:

Timer updateTimer = new Timer(testt, null,
                              TimeSpan.FromMilliseconds(1),   // Delay by 1ms
                              TimeSpan.FromMilliseconds(-1)); // Never repeat

Is a delay of 1ms really useful though? Why not just execute it immediately? If you're really just trying to execute it on a thread-pool thread, there are better ways of achieving that.

like image 132
Jon Skeet Avatar answered Dec 12 '22 03:12

Jon Skeet


System.Timers.Timer aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 60 seconds (60000 milliseconds).
aTimer.Interval = 60000;
//for enabling for disabling the timer.
aTimer.Enabled = true;
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
     //disable the timer
    aTimer.Enabled = false;
    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
 }
like image 22
syedmoulaali Avatar answered Dec 12 '22 02:12

syedmoulaali