Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java how to write a timer

Tags:

java

I wanted to write a timer in java.which will do the following: when program starts,start the timer1 which will stop after 45 mins, at the same time start the second timer, which will stop after 15 mins. at this time the first timer will starts again, and repeat the above loop until the program exits first timer : 45 min (the time I can use computer) second timer: 15 min (the pause time) first timer : 45 min (the time I can use computer) second timer: 15 min (the pause time) first timer : 45 min (the time I can use computer) second timer: 15 min (the pause time)

I dont know how to use the thread and timer (utils,swing) so I tried to use while(true) but the cpu goes up. here is my current code

static int getMinute(){
    Calendar cal=Calendar.getInstance();
    int minute=cal.getTime().getMinutes();
    return minute;
}

public static Runnable clockf(){
    if (endTime>=60){
        endTime=endTime-60;}
    System.out.println(startTime);
    System.out.println(currentTime);
    System.out.println(endTime);

    if(currentTime==endTime){
        pauseStart=getMinute();
        currentTime=getMinute();
        pauseEnd=pauseStart+15;

        if(currentTime==pauseEnd){
            pauseStart=0;
            pauseEnd=0;
            startTime=getMinute();
            currentTime=getMinute();
            endTime=startTime+45;
        }
    }
    else{
        update();
    }

    return null;

}

private static void update() {
    currentTime=getMinute();
    System.out.println(currentTime);
}

public static void main(String[] args) {
    startTime=getMinute();
    currentTime=getMinute();
    endTime=startTime+45;

    Thread t=new Thread(clockf());
    t.setDaemon(true);
    t.start();
    try {
        Thread.currentThread().sleep(1000);//60000

    } catch (InterruptedException e) {
        System.err.println(e);
    }



    }

but it isnt good. are there any way to make the clockf method run only once / min ? or any other way to make that timer runs ?

like image 987
ace Avatar asked Jul 03 '26 07:07

ace


1 Answers

Even though I did not fully understand what you're trying to do Timer and TimerTask should do that for you. Following code has to improved a bit to be runnable, but hopefully shows the principle:

long minute = 1000*60;

Timer timer1 = new Timer();
long delay1 = 45*minute;
Timer timer2 = new Timer();
long delay2 = 15*minute;
TimerTask tt1;
TimerTask tt2;

...

tt1 = new TimerTask()
{
   public void run()
   {
      //do something and:
      timer2.schedule(tt2, delay2);
   }
};

tt2 = new TimerTask()
{
   public void run()
   {
      //do something and:
      timer1.schedule(tt1, delay1);
   }
};

timer1.schedule(tt1, delay1);
like image 127
Kai Huppmann Avatar answered Jul 05 '26 21:07

Kai Huppmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!