Programing

Java에서 타이머를 설정하는 방법은 무엇입니까?

crosscheck 2020. 6. 21. 19:43
반응형

Java에서 타이머를 설정하는 방법은 무엇입니까?


2 분 동안 타이머를 설정하여 데이터베이스에 연결하려고 시도한 다음 연결에 문제가있는 경우 예외를 throw하는 방법은 무엇입니까?


답의 첫 번째 부분은 처음에 그것을 해석 한 방법이었고 몇몇 사람들이 도움이 된 것처럼 보였으므로 주제가 요구하는 것을 수행하는 방법입니다. 질문은 명확 해졌고 그 문제를 해결하기 위해 답변을 확장했습니다.

타이머 설정

먼저 타이머를 만들어야합니다 ( java.util여기서는 버전을 사용하고 있습니다).

import java.util.Timer;

..

Timer timer = new Timer();

일단 작업을 실행하려면 다음을 수행하십시오.

timer.schedule(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000);
// Since Java-8
timer.schedule(() -> /* your database code here */, 2*60*1000);

지속 시간 후에 작업을 반복하려면 다음을 수행하십시오.

timer.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000, 2*60*1000);

// Since Java-8
timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);

작업 시간 초과 만들기

명확한 질문이 요구하는 것을 구체적으로 수행하기 위해, 주어진 기간 동안 작업을 수행하려고 시도하면 다음을 수행 할 수 있습니다.

ExecutorService service = Executors.newSingleThreadExecutor();

try {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            // Database task
        }
    };

    Future<?> f = service.submit(r);

    f.get(2, TimeUnit.MINUTES);     // attempt the task for two minutes
}
catch (final InterruptedException e) {
    // The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
    // Took too long!
}
catch (final ExecutionException e) {
    // An exception from within the Runnable task
}
finally {
    service.shutdown();
}

This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.

One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.


Use this

long startTime = System.currentTimeMillis();
long elapsedTime = 0L.

while (elapsedTime < 2*60*1000) {
    //perform db poll/check
    elapsedTime = (new Date()).getTime() - startTime;
}

//Throw your exception

Ok, I think I understand your problem now. You can use a Future to try to do something and then timeout after a bit if nothing has happened.

E.g.:

FutureTask<Void> task = new FutureTask<Void>(new Callable<Void>() {
  @Override
  public Void call() throws Exception {
    // Do DB stuff
    return null;
  }
});

Executor executor = Executors.newSingleThreadScheduledExecutor();
executor.execute(task);

try {
  task.get(5, TimeUnit.SECONDS);
}
catch(Exception ex) {
  // Handle your exception
}

    new java.util.Timer().schedule(new TimerTask(){
        @Override
        public void run() {
            System.out.println("Executed...");
           //your code here 
           //1000*5=5000 mlsec. i.e. 5 seconds. u can change accordngly 
        }
    },1000*5,1000*5); 

[Android] if someone looking to implement timer on android using java.

you need use UI thread like this to perform operations.

Timer timer = new Timer();
timer.schedule(new TimerTask() {
           @Override
            public void run() {
                ActivityName.this.runOnUiThread(new Runnable(){
                    @Override
                      public void run() {
                       // do something
                      }        
                });
            }
        }, 2000));

참고URL : https://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java

반응형