Execute a method after delay on time only

2019-02-15 00:40发布

问题:

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?

回答1:

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.



回答2:

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);
 }