-1

I want to add a timer to a block of code in java so as to slow down its execution speed. How can I do this using the Timer class, or if there is any other way then how to do it that way? Thank You

  • May be `Thread.sleep(..);` ...? – Trinimon Jun 28 '14 at 08:05
  • No, I dont want to put a "pause", I want to reduce the speed of execution of that block of code... lets say I want the entire block of code to execute in 6 seconds – user3777826 Jun 28 '14 at 08:08
  • putting Thread.sleep will execute it after 6 seconds and not within 6 seconds. I want it to execute within 6 seconds – user3777826 Jun 28 '14 at 08:08
  • Buy an old computer that is slow enough. - There is no such thing in software, except that you may add superfluous statements that just waste cycles. – laune Jun 28 '14 at 08:10
  • Apparently there is, check this out http://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java – user3777826 Jun 28 '14 at 08:12
  • By the way java.util.Timer class is used to schedule a task. – Ashok_Pradhan Jun 28 '14 at 08:13
  • That link "how-to-set-a-timer" eplains how to create time supervision. This is a typical real-time task where something must be done before a deadline, or when you may not keep trying ad infinitum. Your requests ist fundamentally different: you want that code to start at (say) 0:00:00 and do whatever it was written to do and complete it exactly six seconds later ("slow down"). Don't confuse issues! – laune Jun 28 '14 at 08:19
  • Does that answer not answer your question? That's how to do it. – Dylan Gattey Jun 28 '14 at 08:20

1 Answers1

0

In order to postpone the exit of a block of code to exactly 6 seconds after the block has been started, you can do the following:

{ // begin of the "block of code
  long t0 = System.currentTimeMillis();

  // code of the "block of code"

  long t1 = System.currentTimeMillis();
  long delta = 6000 - (t1 - t0);
  if( delta > 0 ){
      Thread.sleep( delta ); 
  }
  // end of the "block of code"
}

Of course, this does not "slow down" the execution of the code as you'd experience it on a slow CPU, but you can't have that anyway.

laune
  • 31,114
  • 3
  • 29
  • 42