参考https://www.php.cn/java/base/435433.html
尝试了多个,觉得ScheduledExecutorService是最好用的,该方法目前写在了主函数中,代码如下
package debug; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class TimeUp { public static void main(String[] args) { //新建定时任务 Runnable runnable = new Runnable() { //run方法中是定时执行的操作 public void run() { System.out.println(new Date()); } }; ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(runnable, 5, 2, TimeUnit.SECONDS); // * 参数一:command:执行线程 // * 参数二:initialDelay:初始化延时 // * 参数三:period:两次开始执行最小间隔时间 // * 参数四:unit:计时单位 } }