2014-10-31 17 views
1

我正在開發一個系統,它必須每N秒定期啓動一個任務(下載文件)。這不是一個問題,我做到了用TimerTimertask如下:如何啓動定時執行但定時執行的定時器

FileTimer rXMLFileTimer; 

private static Timer timer = new Timer("FileReader"); 
rXMLFileTimer = new ReadFileTimer(); 
int myDelay = 30; 
timer.scheduleAtFixedRate(rXMLFileTimer, 0, myDelay * 1000); 

timertask將運行至rXMLFileTimer.cancel()被調用。到現在爲止沒有問題。現在

,已要求該timertask應該運行,直到rXMLFileTimer.cancel()被稱爲給定的時間量。

我的第一種方法(沒有工作)爲實現Future如下:

public class Test { 

public static class MyJob implements Callable<ReadFileTimer> { 

    @Override 
    public ReadFileTimer call() throws Exception { 
     Timer timer = new Timer("test"); 

     ReadFileTimer t = new ReadFileTimer(); 

     int delay = 10; 
     // Delay in seconds 
     timer.schedule(t, 0, delay * 1000); 

     return t; 
    } 
} 

public static void main(String[] args) { 

    MyJob job = new MyJob(); 
    System.out.println(new Date()); 

    Future<ReadFileTimer> control = Executors.newSingleThreadExecutor().submit(job); 

    ReadFileTimer timerTask = null; 
    try { 
     int maxAmountOfTime = 30; 
     timerTask = control.get(maxAmountOfTime, TimeUnit.SECONDS); 

    } catch (TimeoutException ex) { 
     control.cancel(true);   
    } catch (InterruptedException ex) { 

    } catch (ExecutionException ex) {} 

    } 
} 

這不是工作,因爲我不能叫timerTask.cancel()後超時有發生。那麼我的問題是:如何在給定的時間內啓動timerTask

謝謝!

回答

1

爲什麼不只是扔第二個計時器任務取消第一個?例如,此代碼每秒打印日期十秒鐘:

public static void main(String[] args) throws Exception { 
    Timer timer = new Timer(); 
    final TimerTask runUntilCancelledTask = new TimerTask() { 
     @Override 
     public void run() { 
      System.out.println(new Date()); 
     } 
    }; 
    timer.schedule(runUntilCancelledTask, 0, 1000); 
    timer.schedule(new TimerTask() { 
     @Override 
     public void run() { 
      runUntilCancelledTask.cancel(); 
     } 
    }, 10000); // Run once after delay to cancel the first task 
} 
+0

謝謝。這比我想要的要容易得多 – Luixv 2014-11-01 11:57:09