3

I am trying to create a code that calls the system time and updates it every minute. Can anybody give me an example that will steer me in the right direction? thanks

willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
Rafiq Flucas
  • 111
  • 1
  • 8

2 Answers2

5

I think that you're looking for a Timer. It can schedule a task such as updating anything every minute.


public class MyScheduledTask extends TimerTask{
    public void run(){
        System.out.println("Message printed every minute");
    }
}

public class Main{
    public static void main(String... args){
        Timer timer = new Timer();
        timer.schedule(new MyScheduledTask(), 0, 60*1000);
        //Do something that takes time 
    }
}

For the current system time you can use System.currentTimeMillis().


Resources :

Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
  • i see that i would need a timer but wouldn't i need a counter also in order for the time to update every minute – Rafiq Flucas Sep 13 '10 at 19:59
  • The timer.schedule count itself, the `60*1000` argument says it will call the `run()` method of `MyScheduledTask` every 60*1000 milliseconds. – Colin Hebert Sep 13 '10 at 20:02
  • import java.util.Timer; import java.util.TimerTask; public class CAARSCounter_1 extends TimerTask{ public void run(){ System.out.println("Message printed every minute");} public static void currentTimeMillis(){ } public void main(String... args){ Timer timer = new Timer(); timer.schedule(new CAARSCounter_1(),0 , 60*1000);} } – Rafiq Flucas Sep 13 '10 at 20:07
  • You don't have to define your own `currentTimeMillis()`. But it's about right. – Colin Hebert Sep 13 '10 at 20:16
  • Edit your question and put this code in it, and mark it as code so it doesn't wrap like this. – Stephen P Sep 13 '10 at 20:17
  • I seem to have a plethora of questions lol but, how would i get the time to print to the screen every minute – Rafiq Flucas Sep 13 '10 at 20:26
  • You can use either `Date now = new Date()` as suggested in comments and print it or `currentTimeMillis()` to get the currentTime as a long. – Colin Hebert Sep 14 '10 at 20:27
1

If you were just looking to create a timer you could create a Thread to execute every second within an infinite loop

public class SystemTime extends Thread {

    @Override
    public void run(){
        while (true){
            String time = new SimpleDateFormat("HH:MM:ss").format(Calendar.getInstance().getTime());

            System.out.println(time);
            try{
                Thread.sleep(1000);
            } catch (InterruptedException ie){
                return;
            }
        }
    }
}
Squeeky91
  • 11
  • 2