0

I am new to Java and I want to make a program that will execute determined actions if a time is detected.

Example: I start a timer, when 30 segs have gone, display a message, after 3 minutes have gone, execute another action, etc, etc.

How can I do this?

Thank you

Gabriel Luque
  • 117
  • 11

2 Answers2

1

Use the Timer class, you can do something like this:

public void timer() {

    TimerTask tasknew = new MyTask();
    Timer timer = new Timer();

    /* scheduling the task, the first argument is the task you will be 
     performing, the second is the delay, and the last is the period. */
    timer.schedule(tasknew, 100, 100);
}

}

This is an example of a class that extends TimerTask and does something.

 class MyTask extends TimerTask {

        @Override
        public void run() {
            System.out.println("Hello world from Timer task!");

        }
    }

For further reading look into

Timer Docs

Timer schedule example

Eddie Martinez
  • 13,582
  • 13
  • 81
  • 106
0

Using ScheduledExecutorService is one possibility.

See the docs for usage example and more.

import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
    private final ScheduledExecutorService scheduler =
        Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final Runnable beeper = new Runnable() {
            public void run() { System.out.println("beep"); }
        };
        final ScheduledFuture<?> beeperHandle =
            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
        scheduler.schedule(new Runnable() {
            public void run() { beeperHandle.cancel(true); }
        }, 60 * 60, SECONDS);
    } 
}
ekuusela
  • 5,034
  • 1
  • 25
  • 43
  • But how can I create and call BeeperControl object form my main? `class MyClass{ public static void main(String args[]){ ??? } }` – Anchor Mar 20 '19 at 14:41