问题描述:

In my case I created a object and planned to release it after 20 minutes(accuracy is not necessary). I know by using java.util.Timer I can create a timer.But I just want it run once. After that,the timer should stop and been released too.

Is there any way just like setTimeOut() in javascript?

Thanks.

网友答案:
int numberOfMillisecondsInTheFuture = 10000; // 10 sec
Date timeToRun = new Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);
Timer timer = new Timer();

timer.schedule(new TimerTask() {
        public void run() {
            // Task here ...
        }
    }, timeToRun);

Modify above so that you can schedule a job 20 minutes in future.

网友答案:

Use Timer::schedule(TimerTask, long) or look into the ScheduledThreadPoolExecutor or ScheduledExecutorService classes.

网友答案:

You can start a new thread and call sleep with the number of milliseconds to wait, then execute your instructions (on either thread). See http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html for reference, and look at the various online thread tutorials if you need more help.

网友答案:

java.util.Timer has a cancel method in it:

http://download.oracle.com/javase/6/docs/api/java/util/Timer.html#cancel%28%29

However, as far as I know, in timer if you do not specify a period, scheduled task will run only once.

网友答案:
package com.stevej;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class StackOverflowMain {

  public static void main(String[] args) {

    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);

    Runnable myAction = new Runnable() {
      @Override
      public void run() {
        System.out.println("Hello (2 minutes into the future)");
      }
    };

    executor.schedule(myAction, 2, TimeUnit.MINUTES);
  }
}
相关阅读:
Top