溫馨提示×

scheduleatfixedrate是否支持任務取消

小樊
86
2024-09-02 22:59:57
欄目: 編程語言

scheduleAtFixedRate 方法本身不支持任務的取消。但是,你可以使用 ScheduledFuture 對象來取消一個已經調度的任務。

當你使用 scheduleAtFixedRate 方法時,它會返回一個 ScheduledFuture 對象。你可以使用這個對象的 cancel() 方法來取消任務。下面是一個簡單的示例:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduleAtFixedRateExample {
    public static void main(String[] args) {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        Runnable task = () -> System.out.println("Task is running");

        ScheduledFuture<?> scheduledFuture = executor.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Cancel the task
        scheduledFuture.cancel(true);

        executor.shutdown();
    }
}

在這個示例中,我們創(chuàng)建了一個 ScheduledExecutorService,并使用 scheduleAtFixedRate 方法調度一個任務。然后,我們使用 ScheduledFuture 對象的 cancel() 方法在 5 秒后取消任務。

0