How can I update the current time every second?

It is necessary to implement a reminder, accept the current time and write to a variable, it is recorded once, and it is necessary to update the entry in the variable every second.

  • Update time where? In the variable? In the system clock? - Nofate
  • Nofate in a variable - ponpat0ne
  • 3
    For example, run the task in the ScheduledExecutorService at intervals of a second. - Nofate
  • @Nofate please reply. Great solution because - Chubatiy
  • but there are no easier options for me to advise this method, but I am tight and have not yet figured out the streams, and I don’t even wish with desire - ponpat0ne

4 answers 4

You can use the timer:

 String s; public static void main(String[] args) { Timer timer = new Timer(); timer.schedule(new getTimeEverySecond(), 0, 1000); // ставим на выполнение каждую секунду } static class getTimeEverySecond extends TimerTask { public void run() { DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); Date date = new Date(); s = dateFormat.format(date); // каждую секунду обновляем переменную } } 
  • Could be so. Only access to s needs to be synchronized anyway or make it volatile. - Nofate

For the general case of regularly updating the value of a variable.

 private volatile LocalDateTime dateTime; void init() { ScheduledExecutorService service = Executors.newScheduledThreadPool(1); service.scheduleAtFixedRate((() -> dateTime = LocalDateTime.now()), 0, 1, TimeUnit.SECONDS); } 

For a reminder, you can immediately create a one-time task with the desired delay:

 void init() { ScheduledExecutorService service = Executors.newScheduledThreadPool(1); int delay = 100; // таймаут в секундах до наступления уведомления service.schedule(this::doNotify, delay, TimeUnit.SECONDS); } void doNotify() { // тут выполняем логику уведомления } 

    Here's a java

     Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println(new Date()); } }, 0, 1000); 
       int hour, minute, second; for (;;) { TimeUnit.SECONDS.sleep(1); if (second != 59) { second++; } else { second = 0; if (minute != 59) { minute++; } else { minute = 0; if (hour != 23) { hour++; } else { break; } } } } 

      but it is better to use unixtamestamp