class TimerTest01{ public static void main(String[] args) { Timer timer = new Timer(); // Timer timer = new Timer(true);//守护线程 String firstTimeStr = "2021-05-09 17:27:00"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date firstTime = sdf.parse(firstTimeStr); timer.schedule(new MyTimerTask(), firstTime, 1000 * 5);//每5s执行一次 } catch (ParseException e) { e.printStackTrace(); } } } class MyTimerTask extends TimerTask{ @Override public void run() { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = sdf.format(d); System.out.println(time + ":备份日志一次!"); } }