1.1 方式一
public void scheduledExecutorService(){ Runnable runnable = new Runnable() { @Override public void run() { System.out.println("Hello World!"); } }; long delay = 0; long intevalPeriod = 5; ScheduledExecutorService server = Executors.newSingleThreadScheduledExecutor(); /* * runnable 需要执行的任务; * intevalPeriod 每多久执行一次; * delay 第一次延迟多久执行; * TimeUnit.SECONDS代表intevalPeriod,delay的单位为秒。 */ server.scheduleWithFixedDelay(runnable, intevalPeriod, delay, TimeUnit.SECONDS); }1.2 方式二
public static void timerTask(){ TimerTask timerTask = new TimerTask() { @Override public void run() { System.out.println("Hello World"); } }; Timer timer = new Timer(); long delay = 0; long intevalPeriod = 2 * 1000; timer.scheduleAtFixedRate(timerTask, delay, intevalPeriod); }1.3 方式三
public static void crontab(long timeInterval) { Runnable runnable = new Runnable() { @Override public void run() { while (true){ try { Thread.sleep(timeInterval);// 延迟执行 System.out.println("Hello World!"); break; } catch (InterruptedException e){ e.printStackTrace(); } } } }; Thread thread = new Thread(runnable); thread.start(); }