项目中用到了ScheduledExecutorService这里简单写了个demo留以后复习
job工作
package org.ScheduledExecutorService; import java.text.SimpleDateFormat; import java.util.Date; public class RunnableJob implements Runnable{ private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); @Override public void run() { try { Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } System.out.println("The current time is " + sdf.format(new Date()) + "."); } }
测试类
package org.ScheduledExecutorService; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledExecutorServiceTest { private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(10); /** * 初始化延迟1s开始执行,每隔3s重新执行一次任务。 */ public void scheduleAtFixedRateTest() { executor.scheduleAtFixedRate(new RunnableJob(), 1, 3, TimeUnit.SECONDS); } /** * 初始化时延时1s开始执行,本次执行结束后延迟4s开始下次执行。 */ public void scheduleWithFixedDelayTest(){ executor.scheduleWithFixedDelay(new RunnableJob(), 1, 4, TimeUnit.SECONDS); } public void scheduleRunnableTest(){ executor.schedule(new RunnableJob(), 3, TimeUnit.SECONDS); } public void scheduleTest(){ /* executor.schedule(new Callable<V>() { }, delay, unit)*/ } public static void main(String[] args) { ScheduledExecutorServiceTest sest = new ScheduledExecutorServiceTest(); System.out.println("start time is " + sdf.format(new Date())); // sest.scheduleAtFixedRateTest(); // sest.scheduleWithFixedDelayTest(); sest.scheduleRunnableTest(); } }