Java time code

I am trying to create code that calls the system time and updates it every minute. Can someone give me an example that will help me in the right direction? thank

+3
source share
2 answers

I think what you are looking for Timer. He can schedule a task, such as updating something 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 
    }
}

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


Resources:

+5
source

If you just want to create a timer, you can create a thread that will execute every second in 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;
            }
        }
    }
}
+1
source

Source: https://habr.com/ru/post/1764550/


All Articles