簡體   English   中英

ScheduledExecutorService在超時后中斷

[英]ScheduledExecutorService that interrupts after a timeout

我需要實現一個計划的執行程序服務,該服務每隔x秒運行一次線程。 如果花費了y秒以上的時間,則應該中斷線程的執行。 我嘗試使用ScheduledExecutorService實現解決方案,該服務的時間間隔具有可配置的參數,但沒有超時參數。 我有一些想法,我想聽聽您對實施/技術的建議。

這對您有幫助嗎?任務每10秒開始執行一次,大約需要5秒才能完成,當超時(3秒)時您會收到InterruptedException。

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Worker implements Runnable {
    ListeningExecutorService listeningExecutorService;
    ScheduledExecutorService scheduledExecutorService;
    Runnable task;

    public Worker(ListeningExecutorService listeningExecutorService, ScheduledExecutorService scheduledExecutorService, Runnable task) {
        this.listeningExecutorService = listeningExecutorService;
        this.scheduledExecutorService = scheduledExecutorService;
        this.task = task;
    }

    @Override
    public void run() {
        ListenableFuture future = listeningExecutorService.submit(task);
        Futures.withTimeout(future, 3, TimeUnit.SECONDS, scheduledExecutorService);
    }

    public static void main(String[] args) {
        ListeningExecutorService listeningExecutorService = MoreExecutors
            .listeningDecorator(Executors.newCachedThreadPool());
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
        Worker worker = new Worker(listeningExecutorService, scheduledExecutorService, new Runnable() {
            @Override
            public void run() {
                System.out.println("Now begin: " + new Date());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Now end: " + new Date());
            }
        });
        scheduledExecutorService.scheduleAtFixedRate(worker, 0, 10, TimeUnit.SECONDS);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM