从j2se的api文档上查看ScheduledExecutorService的方法都是推迟一段时间然后相隔一段时间之后再去执行,没有想Timer定时器一样的可以在定点时间执行的api,如果也想像Timer那样定时执行就需要对ScheduledExecutorService的方法传入参数处理一下,下面是个人使用ScheduledExecutorService做的每天凌晨3点做的定时执行任务demo
package com.liu.test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class ThreadTest { public static void main(String[] args) { //创建含有三个线程的计划线程池 ScheduledExecutorService service = Executors.newScheduledThreadPool(3); //一天的毫秒数 long oneDay = 24 * 60 * 60 * 1000; //计算初始延迟的毫秒数 long initDelay = getTimeMillis("3:00:00") - System.currentTimeMillis(); initDelay = initDelay > 0 ? initDelay : initDelay + oneDay; List<String> list1 = new LinkedList<String>(); list1.add("第一个 :"); List<String> list2 = new LinkedList<String>(); list2.add("第二个 "); List<String> list3 = new LinkedList<String>(); list3.add("第三个 "); //执行三个任务 ScheduledFuture future = service.scheduleAtFixedRate(new RunnableTest(list1), initDelay, oneDay, TimeUnit.MILLISECONDS); service.scheduleAtFixedRate(new RunnableTest(list2), initDelay, oneDay, TimeUnit.MILLISECONDS); service.scheduleAtFixedRate(new RunnableTest(list3), initDelay, oneDay, TimeUnit.MILLISECONDS); } private static long getTimeMillis(String time) { // TODO Auto-generated method stub SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd"); try { long fixedTime = dateFormat.parse(dayFormat.format(new Date())+" "+time).getTime(); return fixedTime; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } } package com.liu.test; import java.util.List; public class RunnableTest implements Runnable { private List<String> list; public RunnableTest() { } public RunnableTest(List<String> list){ this.list = list; } @Override public void run() { // TODO Auto-generated method stub for(int i=0;i<10;i++){ if(i%3 == 0){ try { Thread.sleep(3000); System.out.println(list.get(0)+ "3 number +" + i); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }