开发者

How to run a timer?

I want to run a timer which say开发者_如何学Pythons time is expired after 30 seconds,how can do so? Some task to be run only for some seconds then showing expired, how can i do so?


I'd recommend using ScheduledExecutorService from the java.util.concurrent package, which has a richer API than other Timer implementations within the JDK.

// Create timer service with a single thread.
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();

// Schedule a one-off task to run in 10 seconds time.
// It is also possible to schedule a repeating task.
timer.schedule(new Callable<Void>() {
  public Void call() {
    System.err.println("Expired!");

    // Return a value here.  If we know we don't require a return value
    // we could submit a Runnable instead of a Callable to the service.
    return null;
  }
}, 10L, TimeUnit.SECONDS);


The actionPerformed method is called after 30 sec

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.Timer;

public class TimerExample {
    public static void main(String args[]) {
        new JFrame().setVisible( true );
        ActionListener actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println( "expired" );
            }
        };
        Timer timer = new Timer( 30000, actionListener );
        timer.start();
    }
}


Use Timer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜