简体   繁体   中英

C# System.Timers.Timer auto-shutdown?

I have a Timer which kicks off and does it's job indefinitely in it's own thread until something happens in the main thread to disable it, in which case a different one will be enabled. This works perfectly. The only problem is that I want to make COMPLETELY sure the second timer doesn't run for too long.

Is there a way to make a timer automatically disable after, say, 10 minutes if it doesn't receive a specific shutdown command due to some malfunction?

I see that the class has a InitializeLifetimeService method. It sounds like it could help but I have no idea how to work it.

Thanks guys and gals :)

为什么不让它在每次迭代时都向全局变量+1(例如,是否每秒滴答一次),让计时器每隔一个滴答检查一次变量,一旦var达到600,就告诉计时器禁用自身。

Just declare a Class variable and set it when you start the timer to DateTime.Now. Then include this in your timer:

DateTime time = DateTime.Now;

   private void timer1_Tick(object sender, EventArgs e)
   {
       if (DateTime.Compare(DateTime.Now, time.AddMinutes(10)) > 0)
       {
           timer1.Stop();
       }

       // timer code
   }

You might consider starting a third Timer when you start the second one to disable it after a given time.

        Timer t1 = new Timer(1000); // fire every second
        Timer t2 = new Timer(60000); // fire after 10 minutes
        t2.Elapsed += (o, e) => t1.Stop(); // disable timer 1 when timer 2 is elapsed

        t1.Start();
        t2.Start();

The example above makes use of System.Timers.Timer by the way. If you are using System.Threading.Timer you might consider a switch there as well for surprisingly enough System.Timers.Timer is the one who is threadsafe by nature, where System.Threading.Timer is not.

Quite good overview can be found here: http://msdn.microsoft.com/en-us/magazine/cc164015.aspx

EDIT for clarity: the line

t2.Elapsed += (e, o) => t1.Stop();

could also be written as

 t2.Elapsed += new ElapsedEventHandler(t2_Elapsed);

followed by

void t2_Elapsed(object sender, ElapsedEventArgs e)
{
    t1.Stop();
}

which is what you actually get when hitting Ctrl+Space in Visual Studio, given hat you have access to t1 in the lower method.

Assign an elapsed event handler and global Boolean

     Private Boolean eOccured = False;

     System.Timers.Timer aTimer = new System.Timers.Timer();
     aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
     aTimer.Interval = 600000; //milliseconds(10 min)
     aTimer.Enabled = True;

... Code activates bool if successful ...

Then stop the timer on event trigger.

    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        If (eOccured)
        {
            aTimer.Stop();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM