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.
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); // каждую секунду обновляем переменную } } 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
Source: https://ru.stackoverflow.com/questions/574908/
All Articles
ScheduledExecutorServiceat intervals of a second. - Nofate ♦