任務調度有幾種實現方式:java
private static final Long TwoSecond = 2 * 1000L; private static final Long ThreeSecond = 3 * 1000L; public static void main(String[] args) throws Exception { TimerTask task = new TimerTask() { @Override public void run() { try { System.out.printf("這是我這個任務處理的內容\n"); } catch (Exception e) {} } }; Timer timer = new Timer(); timer.schedule(task, TwoSecond, ThreeSecond); }
結果入下:ide
private static final Long TwoSecond = 2L; private static final Long ThreeSecond = 3L; public static void main(String[] args) throws Exception { ScheduledExecutorService service = Executors.newScheduledThreadPool(2); ScheduledFuture<String> futureList = service.schedule( new Sing("K歌之王"), TwoSecond, TimeUnit.SECONDS); ScheduledFuture<String> futureList2 = service.schedule( new Sing("淘汰"), ThreeSecond, TimeUnit.SECONDS); service.scheduleWithFixedDelay( new Sing2("簡單愛"), ThreeSecond, TwoSecond, TimeUnit.SECONDS); System.out.println(futureList.get()); System.out.println(futureList2.get()); } public static class Sing implements Callable<String> { private String song = null; Sing(String song) { this.song = song; } @Override public String call() throws Exception { System.out.printf("singing:"+ song +"\n"); return song; } } public static class Sing2 implements Runnable { private String song = null; Sing2(String song) { this.song = song; } @Override public void run() { System.out.printf("run singing:"+ song +"\n"); } }
結果以下:this