这是最多见的,建立一个thread,而后让它在while循环里一直运行着,经过sleep方法来达到定时任务的效果。这样能够快速简单的实现,代码以下:java
public class Task1 { public static void main(String[] args) { // run in a second final long timeInterval = 1000; Runnable runnable = new Runnable() { public void run() { while (true) { // ------- code for task to run System.out.println("Hello !!"); // ------- ends here try { Thread.sleep(timeInterval); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread = new Thread(runnable); thread.start(); } }
上面的实现是很是快速简便的,但它也缺乏一些功能。
用Timer和TimerTask的话与上述方法相比有以下好处:安全
在实现时,Timer类能够调度任务,TimerTask则是经过在run()方法里实现具体任务。
Timer实例能够调度多任务,它是线程安全的。
当Timer的构造器被调用时,它建立了一个线程,这个线程能够用来调度任务:并发
import java.util.Timer; import java.util.TimerTask; public class Task2 { public static void main(String[] args) { TimerTask task = new TimerTask() { @Override public void run() { // task to run goes here System.out.println("Hello !!!"); } }; Timer timer = new Timer(); long delay = 0; long intevalPeriod = 1 * 1000; // schedules the task to be run in an interval timer.scheduleAtFixedRate(task, delay, intevalPeriod); } // end of main }
ScheduledExecutorService是从Java SE 5的java.util.concurrent里,作为并发工具类被引进的,这是最理想的定时任务实现方式。
相比于上两个方法,它有如下好处:ide
咱们经过ScheduledExecutorService#scheduleAtFixedRate展现这个例子,经过代码里参数的控制,首次执行加了delay时间:工具
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Task3 { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { // task to run goes here System.out.println("Hello !!"); } }; ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); } }