How to start a timer?

I want to start a timer that says that time is running out after 30 seconds, how to do it? Some task should only be started in a few seconds and then expired, how can I do this?

+3
source share
3 answers

I recommend using ScheduledExecutorServicefrom a package java.util.concurrentthat has a richer API than other implementations Timerwithin 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);
+7
source

The actionPerformed method is called after 30 seconds.

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();
    }
}
+4
source

Use Timer .

0
source

Source: https://habr.com/ru/post/1731341/


All Articles