Making a program run for 5 minutes

前端 未结 5 1986
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 14:03

So I wanted to try out something for a bit with the Timer and TimerTask classes.

I was able to get a line of code to execute after 30 seconds elapsed. What I\'ve been t

5条回答
  •  天涯浪人
    2021-01-26 14:25

    I don't know if this solution has problems with the garbage collector or not, but I throw it in here anyways. Maybe someone clears that out, and I learn something as well. Basically a timer sets a new timer if there is time left, and it should stop after 5 minutes.

    Main.java:

    public class Main {
        public static void main(String[] args) {
            MyTimer myTimer = new MyTimer(300000,30000);
            myTimer.startTimer();
        }
    }
    

    MyTimer.java:

    import java.util.Timer;
    import java.util.TimerTask;
    
    public class MyTimer {
        private int totalRunningTime;
        private int currentTime = 0;
        private int intervalTime;
    
        private Timer timer = new Timer();
    
        public MyTimer(int totalRunningTime, int intervalTime) {
            this.totalRunningTime = totalRunningTime;
            this.intervalTime = intervalTime;
        }
    
        public void startTimer() {
            startTimer(intervalTime);
        }
    
        private void startTimer(int time) {
            timer.schedule(new TimerTask() {
                public void run() {
    
                    if (currentTime <= totalRunningTime - intervalTime) {
                        printTimeSinceLast(intervalTime / 1000);
                        currentTime += intervalTime;
                        startTimer(intervalTime);
                    } else if (currentTime < totalRunningTime) {
                        int newRestIntervalTime = totalRunningTime - currentTime;
                        printTimeSinceLast(newRestIntervalTime / 1000);
                        currentTime += newRestIntervalTime;
                        startTimer(newRestIntervalTime);
                    }
                }
            }, time);
        }
    
        private void printTimeSinceLast(int timeSinceLast) {
            System.out.println(timeSinceLast + " seconds later.");
        }
    }
    

提交回复
热议问题