好久没写笔记了,变懒了!
java定时运行的三个案例:
一, 通过sleep方法来达到定时任务的效果
public class testTime { public static void main(String[] args) { // 设定时间间隔为1秒 final long timeInterval = 1000; Runnable runnable = new Runnable() { public void run() { while (true) { // 执行任务 System.out.println("Hello !!"); try { Thread.sleep(timeInterval); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread = new Thread(runnable); thread.start(); } }
二,TimerTask
public class testTime2 { public static void main(String[] args) { TimerTask task = new TimerTask() { public void run() { System.out.println("执行!"); } }; Timer timer = new Timer(); long delay = 0; long intevalPeriod = 1 * 1000; timer.scheduleAtFixedRate(task, delay, intevalPeriod); } }
三,ScheduledExecutorService
public class testTime3 { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { System.out.println("执行!"); } }; ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); // “10”延时时间,“1”为定时执行的间隔时间, TimeUnit.SECONDS为时间单位 service.scheduleAtFixedRate(runnable, 10, 1, TimeUnit.SECONDS); } }
以上三个案例笔者均已验证!