Rafiq Flucas
Rafiq Flucas

Reputation: 121

Time Code in Java

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

Upvotes: 3

Views: 2294

Answers (2)

Squeeky91
Squeeky91

Reputation: 11

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;
            }
        }
    }
}

Upvotes: 1

Colin Hebert
Colin Hebert

Reputation: 93157

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 :

Upvotes: 5

Related Questions