定时任务
public class TestTimer2 {
/** * 以固定周期执行任务 * 参数:Runnable ,多长时间开始,与下次任务的周期,时间单位 * */ public void executeFixedRate() { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleAtFixedRate( new ThreadSer(), 0, 1000, TimeUnit.MILLISECONDS); while(true){ } } /** * * 本次任务执行完成后,延迟设定的时间后,才会执行新的任务 */ public void executeFixedDelay() { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.scheduleWithFixedDelay( new ThreadSer(), 0, 1000, TimeUnit.MILLISECONDS); while(true){ } } /** * 延迟多少时间后,执行,只执行一次 */ @Test public void testSchedule() { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); executor.schedule( new ThreadSer(), 1000, TimeUnit.MILLISECONDS); while(true){ } } class ThreadSer implements Runnable { public void run() { System.out.println("实现Runnable:" + System.currentTimeMillis()/1000); } } //TimerTask implements Runnable class TimeSer extends TimerTask{
@Override public void run() { System.out.println("继承TimeSer:" + System.currentTimeMillis()/1000); } } }