溫馨提示×

scheduleAtFixedRate在Java中如何使用

小樊
128
2024-06-27 10:12:22
欄目: 編程語言

在Java中,可以使用ScheduledExecutorService接口的scheduleAtFixedRate方法來創建一個定時任務,該任務會以固定的時間間隔重復執行。

下面是一個示例代碼,演示了如何使用scheduleAtFixedRate方法:

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 executor = Executors.newScheduledThreadPool(1);

        // 創建一個定時任務,每隔1秒執行一次
        executor.scheduleAtFixedRate(() -> {
            System.out.println("Task is running...");
        }, 0, 1, TimeUnit.SECONDS);

        // 等待一段時間后關閉Executor
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        executor.shutdown();
    }
}

在上面的示例中,我們創建了一個ScheduledExecutorService對象,并使用scheduleAtFixedRate方法創建了一個定時任務,該任務每隔1秒執行一次。在任務執行期間,控制臺會輸出"Task is running…"。最后,我們等待5秒后關閉了Executor。

需要注意的是,scheduleAtFixedRate方法的第一個參數是一個Runnable對象,表示要執行的任務;第二個參數是初始延遲時間;第三個參數是重復執行的時間間隔;第四個參數是時間單位。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女