是的,ScheduledExecutorService 可以重復執行任務。它是一個接口,擴展了 ExecutorService 接口,提供了定時執行任務的功能。你可以使用 scheduleAtFixedRate() 或 scheduleWithFixedDelay() 方法來安排任務重復執行。
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit):此方法會在給定的初始延遲后開始執行任務,然后按照固定的頻率(周期)重復執行任務。即使任務的執行時間超過了周期,下一個任務也會立即開始執行。
scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit):此方法會在給定的初始延遲后開始執行任務,然后在每次任務執行完成后,等待固定的延遲時間再執行下一次任務。
這兩個方法的區別在于,scheduleAtFixedRate() 會盡量按照固定的頻率執行任務,而 scheduleWithFixedDelay() 會在每次任務執行完成后等待固定的延遲時間再執行下一次任務。
下面是一個簡單的示例,展示了如何使用 ScheduledExecutorService 重復執行任務:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledTaskExample {
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
Runnable task = () -> System.out.println("Task executed at: " + System.currentTimeMillis());
// 每隔 5 秒執行一次任務
executorService.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
}
}
請注意,在實際應用中,你可能需要根據具體需求選擇合適的方法,并在適當的時候關閉 ScheduledExecutorService。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。