2012-10-23 8 views
7

Więc próbuję dowiedzieć się, jak stworzyć czasomierz, natknąłem się na to: using ScheduledExecutorService to start and stop timerTworzenie timer ScheduledExecutorService

Przykładem mają wydaje się całkiem dobrze. Zastanawiam się tylko, czy jestem wykorzystując to poprawnie:

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"); 
    } 
    } 

} 

A oto test:

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(); 

} 

To wydaje się działać, jestem potęga brakowało czegoś, co muszę, to jest moja pierwsza praca z usługą ScheduledExecutorService Czy widzicie jakieś problemy z tym kodem? Nie chcę, aby był konflikt z kolizją wątku.

+0

Zamiast prosić ludzi, aby przejrzeli kod, dobrze byłoby, gdybyś mógł krótko poinformować o tym, co robi Twój kod i gdzie zmierzysz się z problemem. – Arham

Odpowiedz

5

Z automatycznie otrzymujesz funkcję timera. Nie potrzebujesz go jawnie, chyba że masz coś, czego nie może dostarczyć ScheduleExecutorService. np. Powiedzmy, że chcesz rozpocząć zadanie po początkowym opóźnieniu wynoszącym 10 sekund, a następnie kolejne opóźnienia o 5 sekund każde.

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

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

Potrzebuję wykonać timer, który zresetuje timer, gdy nie upłynie limit czasu (pewne zadanie kończy się, zanim upłynie limit czasu). Wiem, jak zainicjować nowy harmonogram i jak go zakończyć. Jak byś to zresetował? I jak byś to powstrzymał? Może to powinno być moje pytanie. Nie sądzę, aby całkowicie zakończyć harmonogramu jest to, co chcę. – echew

+0

Dzięki, myślę, że po drugim czytaniu ta odpowiedź pomogła. – echew

+0

Cieszę się, że to wiem !! :) – Arham