2012-08-03 68 views
3

我有一個java調度程序的問題,我的實際需要是我必須在特定的時間開始我的過程,並且我會在特定的時間停止,我可以在特定的時間開始我的過程,但我無法阻止我的過程時間,如何指定進程在調度程序中運行多長時間,(這裏我不會放),任何人都有這方面的建議。如何在特定時間安排任務?

import java.util.Timer; 
import java.util.TimerTask; 
import java.text.SimpleDateFormat; 
import java.util.*; 
public class Timer 
{ 
    public static void main(String[] args) throws Exception 
    { 

        Date timeToRun = new Date(System.currentTimeMillis()); 
        System.out.println(timeToRun); 
        Timer timer1 = new Timer(); 
        timer1.schedule(new TimerTask() 
        { 
        public void run() 
           { 

         //here i call another method 
         } 

        } }, timeToRun);//her i specify my start time 


      } 
} 

回答

10

你可以使用一個ScheduledExecutorService 2時間表,一個運行的任務和一個阻止它 - 看一個簡單的例子如下:

public static void main(String[] args) throws InterruptedException { 
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2); 

    Runnable task = new Runnable() { 
     @Override 
     public void run() { 
      System.out.println("Starting task"); 
      scheduler.schedule(stopTask(),500, TimeUnit.MILLISECONDS); 
      try { 
       System.out.println("Sleeping now"); 
       Thread.sleep(Integer.MAX_VALUE); 
      } catch (InterruptedException ex) { 
       System.out.println("I've been interrupted, bye bye"); 
      } 
     } 
    }; 

    scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS); //run task every second 
    Thread.sleep(3000); 
    scheduler.shutdownNow(); 
} 

private static Runnable stopTask() { 
    final Thread taskThread = Thread.currentThread(); 
    return new Runnable() { 

     @Override 
     public void run() { 
      taskThread.interrupt(); 
     } 
    }; 
}