[Java]如何安排任务间隔运行
應用程序中經常需要在后臺運行某些特定任務以在一定間隔內完成某些工作。 該示例可以是,服務在后臺運行以清理應用程序,就像我們有Java Garbage集合一樣。
在本文中,我將向您展示3種不同的方法來實現這一目標
他們如下
- 使用簡單的線程
- 使用TimerTask
- 使用ScheduledExecutorService
使用簡單的線程
這非常簡單,它創建了一個簡單的線程,使用while循環使其永遠運行,并利用sleep方法放置兩次運行之間的間隔。
這是實現它的快捷方法
以下是此代碼。
public class Task1 {public static void main(String[] args) {// run in a secondfinal long timeInterval = 1000;Runnable runnable = new Runnable() {public void run() {while (true) {// ------- code for task to runSystem.out.println("Hello !!");// ------- ends heretry {Thread.sleep(timeInterval);} catch (InterruptedException e) {e.printStackTrace();}}}};Thread thread = new Thread(runnable);thread.start();} }使用Timer和TimerTask
我們看到的先前方法是最快的方法,但是缺少一些功能
與以前相比,這具有更多的好處,如下所示
- 控制何時啟動和取消任務
- 如果需要,可以延遲首次執行,這很有用
在這種情況下,我們使用Timer類進行調度,并使用TimerTask封裝要在其run()方法中執行的任務。
計時器實例可以共享以計劃多個任務,并且它是線程安全的。
調用Timer構造函數時,它將創建一個線程,并且該單個線程可用于任何任務調度。
出于我們的目的,我們使用Timer#scheduleAtFixedRate
以下代碼顯示了Timer和TimerTask的用法
import java.util.Timer; import java.util.TimerTask;public class Task2 {public static void main(String[] args) {TimerTask task = new TimerTask() {@Overridepublic void run() {// task to run goes hereSystem.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 }這些類是JDK 1.3中存在的類。
使用ScheduledExecutorService
這是Java SE 5中的java.util.concurrent作為并發實用程序引入的。 這是實現目標的首選方式。
與以前的解決方案相比,它具有以下優點
- 與TImer的單線程相比,線程池用于執行
- 提供延遲第一次執行的靈活性
- 提供良好的約定以提供時間間隔
以下代碼顯示了相同的用法,
在這里,我們使用ScheduledExecutorService#scheduleAtFixedRate ,如圖所示,它將param作為可運行的,我們要運行哪段代碼,首次執行的初始延遲
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 hereSystem.out.println("Hello !!");}};ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);} }翻譯自: https://www.javacodegeeks.com/2014/04/java-how-to-schedule-a-task-to-run-in-an-interval.html
總結
以上是生活随笔為你收集整理的[Java]如何安排任务间隔运行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (linux的ftp权限)
- 下一篇: 使用Java 8和Lambda简化Rea