How to create a stopwatch in JAVA?

Asked

Viewed 4,684 times

4

I would like to determine how long one image should stay until it returns to the other. Is there a class for that? Otherwise, how to create?

Note: Preferable the absence of Threads.

  • Why the absence of "Threads"? Internally many codes and libraries use Thread :p

  • It’s just that for the program I’m doing, the threads don’t seem right...

1 answer

8


To execute commands after a certain time, you can use the class java.util.Timer.

For example:

new java.util.Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        //executar ação aqui
    }
}, 1000); //executar após 1 segundo

If you prefer a simplified version:

Timer cronometro = new Timer();
TimerTask tarefa = new TimerTask() {
    @Override
    public void run() {
        //executar ação aqui
    }
};
int milissegundos = 1000;
cronometro.schedule(tarefa, milissegundos);

Explanation

Basically the object Timer allows scheduling a task to run after a period of time.

So to define which task we want to perform we need to pass an object that contains the action. In this case, it is an implementation in the method run of TimerTask.

Finally, we spend the time in milliseconds, that is, each 1000 units is equivalent to one second of waiting.

Repetition at regular intervals

The class Timer also allows repeating the task in predefined time intervals, adding a third parameter with the interval between executions.

Example:

int milissegundos = 1000;
int intervalo = 10000;
cronometro.schedule(tarefa, milissegundos, intervalo);

In this example above, the timer waits a second, performs the task, waits 10 seconds, performs the task again and continues to do so.

The time span between the end of one run and the beginning of the next one is exactly 10 seconds. So if one task takes 5 seconds, the time between one to start and the other will be 15 seconds.

Repetition with regular times

The method scheduleAtFixRate allows scheduling executions at regular times:

int milissegundos = 1000;
int intervalo = 10000;
cronometro.scheduleAtFixRate(tarefa, milissegundos, intervalo);

This means that the first task will run after 1 second and the next 10 seconds after the first. It doesn’t matter if the first task takes 2 or 5 seconds. This type of timer makes the interval between the beginning of a run and the beginning of the next run exactly 10 seconds, regardless of how long a task may take.

Alternative

If you don’t worry about using a little bit of threads, though grazed, the class ScheduledExecutorService is also interesting.

    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    Runnable tarefa = new Runnable() {
        @Override
        public void run() {
            //executar ação aqui
        }
    };
    scheduler.schedule(tarefa, 1, TimeUnit.DAYS);

Basically you instantiate the scheduler and then pass to it a task to be executed after a period.

The difference is that you can specify the unit of time, so it is quite useful to avoid absurd calculations with milliseconds turning days, months or years.

In the same way as the Timer, this class provides methods for running at regular intervals, as follows:, scheduleAtFixedRate and scheduleWithFixedDelay. The names are self-explanatory if you understand the concepts I explained above about the Timer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.