Actually a subject. But an option:

st = System.nanoTime(); //что-то делаю end = System.nanoTime(); 

not suitable, because it gives time after completion of all methods. I need to detect, say, 1 minute from the start of the program, if the program runs longer, then forcibly exit, regardless of the completion of the methods. Can somehow detect the execution time of the main thread?

1 answer 1

For example, you can use the method with System.currentTimeMills() :

 long start = System.currentTimeMillis(); long end = start + 60*1000; // 60 секунд* 1000 мс/сек while (System.currentTimeMillis() < end) { // work hard, play hard } 

A source.


You can exit the program from another Thread :

 public class ExitAfterMinute { public static void main(String args[]) { new Thread(new Runnable() { public void run() { try { Thread.sleep(60000); // минута в милисекундах } catch (InterruptedException e) { e.printStackTrace(); } System.exit(0); } }).start(); while (true) { System.out.println("I'm doing something"); } } } 

Or using a timer:

 import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class TimedExit { Timer timer = new Timer(); TimerTask exitApp = new TimerTask() { public void run() { System.exit(0); } }; public TimedExit() { timer.schedule(exitApp, new Date(System.currentTimeMillis() + 60 * 1000)); } } 

A source.

  • It seems that the body can take more than a minute of time. But will not be interrupted. - DimXenon
  • @DimXenon yes, right, added the answer. - Denis
  • See, if using the flow method, then in a while loop (true) {System.out.println ("I'm doing something"); } something will be executed within one minute, i.e. it turns out if I call several methods and they finish their work in less than one minute, then they will be called again, because is the loop endless? Well, I need them to run once and that’s all, if they have time for 1 minute - R.Skidan
  • @ R.Skidan in this case, you can put the flag on execution - executed, int flag made equal to 1. Enter the cycle if flag == 0 . - Denis
  • I do not understand the general meaning of the cycle. Can I do this? public static void main (String args []) {new Thread (new Runnable () {public void run () {try {Thread.sleep (60000);} catch (InterruptedException e) {e.printStackTrace ();} System. out.printf ("did not have time"); System.exit (0);}}). start (); // make the world better. when done and managed <less than 1 minute, complete - System.exit (0); } - R.Skidan