/** * 用线程池启动定时器 * @param args */ public static void main(String[] args) { //10秒启动 Executors.newScheduledThreadPool(3).schedule(new Runnable() { @Override public void run() { System.out.println("start-up success"); } }, 10, TimeUnit.SECONDS); //10秒后启动,并且以后的每两秒启动一次 Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("start - up success"); } }, 10, 2, TimeUnit.SECONDS); //几天以后执行 Date date = new Date(); //代表某一天 Executors.newScheduledThreadPool(3).schedule(new Runnable() { @Override public void run() { System.out.println("start-up success"); } }, date.getTime()-System.currentTimeMillis(), TimeUnit.MILLISECONDS); }
停止定时任务使用schedule返回的ScheduledFuture对象取消任务执行。