2012-08-03 53 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(); 
     } 
    }; 
}