使用Timer创建定时器

public class TimerTask {

    public static void main(String[] args) {
        Timer timer = new Timer();
           
        // 第2个参数表示N毫秒后开始执行,第3个参数表示定时周期
        timer.scheduleAtFixedRate(new java.util.TimerTask() {
            @Override
            public void run() {
                System.out.println(String.format("现在时间是 %s", LocalDateTime.now(ZoneId.of("+8")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            }
        }, 1000, 1000);
    }
}

但是强烈建议使用ScheduledExecutorService代替Timer

猜你喜欢

转载自www.cnblogs.com/esrevinud/p/13376418.html