2012-10-23 34 views
7

Vì vậy, tôi đang cố gắng để tìm ra cách để tạo ra một bộ đếm thời gian, tôi đi qua này: using ScheduledExecutorService to start and stop timerTạo một bộ đếm thời gian với ScheduledExecutorService

Ví dụ họ có vẻ làm việc khá tốt. Tôi chỉ tự hỏi nếu tôi sử dụng này một cách chính xác:

public class TimerTest 
{ 
    private ScheduledExecutorService es = null; 
    private boolean timeIsUp = false; 
    private ScheduledFuture futureHandler = null; 
    private TimeKeeper timeKeeper = null; 
    private String subject = ""; 
    private int siteNo; 
    private long time; 
    private boolean stop; 




public void endTimer() 
{ 
    System.out.println("we should shutdown everything here"); 
    es.shutdownNow(); 
} 

public boolean stopTimer() 
{ 

    if (timeKeeper != null) 
    { 
     timeKeeper.deactivate(); 
    } 
    futureHandler.cancel(true); 
return true; 

} 
public boolean isTimeup() 
{ 
    return timeKeeper.isTimeUp(); 
} 
public void startTimer(long mseconds, String subj, int sNo) 
{ 
    subject = subj; 
    siteNo = sNo; 
    time = mseconds; 
    timeKeeper = new TimeKeeper(); 
    callScheduler(mseconds); 

} 

public boolean isTimerRunning() 
{ 
    return (es.isShutdown() || es == null); 

} 
public void resetTimer(long t) 
{ 
    stopTimer(); 
    callScheduler(t); 
} 

public void resetTimer() 
{ 

    resetTimer(time); 
} 

private void callScheduler(long mseconds) 
{ 
    if (es == null) 
     es = Executors.newScheduledThreadPool(3); 
    timeKeeper = new TimeKeeper(); 
    futureHandler = es.schedule(timeKeeper, mseconds, TimeUnit.MILLISECONDS); 

} 


private class TimeKeeper implements Runnable { 
    //volatile for thread-safety 

    private volatile boolean isActive = true; 
    private volatile boolean isTimeUp = false; 
    public void run() { 
     if (isActive){ 
      callAlert(); 
      isTimeUp = true; 
     } 
    } 
    public void deactivate(){ 
     isActive = false; 
    } 

    public boolean isTimeUp() 
    { 
     return isTimeUp; 
    } 
    private void callAlert() 
    { 
     System.out.println("you are in the callAlert method"); 
    } 
    } 

} 

Và đây là thử nghiệm:

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    long pastTime = System.currentTimeMillis(); 
    TimerTest timer = new TimerTest(); 
    timer.startTimer(15000, "bh", 1); 
    long time; 
    int count =0; 
    boolean stop = false; 
    while(true) 
    { 

     try { 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     time = System.currentTimeMillis() - pastTime; 

     if (time > 3000) 
     { 
      if (!stop){ 
       System.out.println("we are reseting the timer"); 
       timer.resetTimer(4000); 

       timer.stopTimer(); 
       try { 
        Thread.sleep(3995); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       break; 

      } 
      stop = true; 


     } 
     if (timer.isTimeup()) 
     { 
      System.out.println("our time is up"); 
      timer.endTimer(); 
      break; 
     } 
     if (!stop) 
      System.out.println("hello"); 
     else 
     { 
      if (count == 0) 
       System.out.println("we wait 10 seconds from now"); 
      count++; 
     } 


    } 
    timer.resetTimer(1200); 
    while (true) 
    { 
     if (timer.isTimeup()) 
     { 
      timer.isTimeup(); 
      System.out.println("breaking after time is up"); 
      break; 
     } 
    } 
    timer.endTimer(); 

} 

Điều này dường như làm việc, tôi là sức mạnh của một cái gì đó bỏ lỡ mà tôi cần, này là lần đầu tiên tôi làm việc với ScheduledExecutorService Các bạn có thấy bất kỳ vấn đề nào với mã này không? Tôi không muốn có xung đột với xung đột chuỗi.

+0

Thay vì yêu cầu mọi người xem mã của bạn, sẽ tốt nếu bạn có thể tóm tắt về mã của bạn đang làm gì và bạn gặp phải vấn đề ở đâu. – Arham

Trả lời

5

Với ScheduledExecutorService bạn sẽ tự động nhận được tính năng hẹn giờ. Bạn không cần nó một cách rõ ràng trừ khi bạn có một cái gì đó mà ScheduleExecutorService không thể cung cấp. ví dụ: Giả sử bạn muốn bắt đầu một tác vụ sau thời gian trễ ban đầu là 10 giây và sau đó là sự chậm trễ tiếp theo 5 giây.

public void init() { 
    executor = new ScheduledThreadPoolExecutor(corePoolSize); 
    executor.scheduleWithFixedDelay(new WorkerThread(), 10, 5, TimeUnit.SECONDS); 
} 

public void end() { 
    executor.shutdown(); 
} 
+0

Tôi cần phải thực hiện bộ hẹn giờ sẽ đặt lại bộ hẹn giờ khi nó không hết thời gian chờ (Một tác vụ nhất định kết thúc trước khi bộ hẹn giờ hết giờ). Tôi biết cách bắt đầu một bộ lập lịch mới và cách kết thúc nó. Làm thế nào bạn sẽ thiết lập lại nó ?, và làm thế nào bạn sẽ ngăn chặn nó? Có lẽ đó là câu hỏi của tôi. Tôi không nghĩ rằng kết thúc lịch trình hoàn toàn là những gì tôi muốn. – echew

+0

Cảm ơn, tôi nghĩ sau một giây đọc câu trả lời đó đã giúp ích. – echew

+0

vui mừng khi biết điều đó !! :) – Arham

Các vấn đề liên quan