Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Code in Java

Tags:

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

like image 900
Rafiq Flucas Avatar asked Sep 17 '26 21:09

Rafiq Flucas


2 Answers

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 :

  • javadoc - Timer
  • javadoc - System.currentTimeMillis()
like image 139
Colin Hebert Avatar answered Sep 19 '26 21:09

Colin Hebert


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;
            }
        }
    }
}
like image 26
Squeeky91 Avatar answered Sep 19 '26 20:09

Squeeky91