2011-09-28 76 views
0

在我的情况下,我创建了一个对象,并计划在20分钟后释放它(不需要精度)。我知道通过使用java.util.Timer我可以创建一个计时器。但我只想让它运行一次。之后,计时器应该停止并释放。如何设置一个计时器,但不要重复运行

有没有什么办法就像在setTimeOut()在JavaScript?

谢谢。

回答

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

修改上面的内容以便将来可以安排20分钟的工作。

0
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); 
    } 
} 
相关问题