This time, I will explain how to implement Java timer processing. In this sample, we will implement the process of creating a specific task and executing that task after a few seconds.
After that, it will be explained in the following versions and environments.
IDE:eclipse Java version: 8
Then, I will explain it immediately.
The folder structure of the sample source created this time is as follows.
First, when implementing timer processing, create an object of the TimerTask class.
Then, put the run () method in the TimerTask class and implement the process you want to execute with the timer.
Finally, create an object of the timer class and specify the task and timer time you want to execute with the schedule method of the timer class.
TimerTask task = new TimerTask() {
public void run() {
//The process you want to execute with the timer
}
};
Timer timer = new Timer();
timer.schedule(task,Timer time(ms));
Using the above syntax, let's implement the process that outputs the phrase "The task has been executed" to the console after 3 seconds.
SampleTimer.java
package main;
import java.util.Timer;
import java.util.TimerTask;
public class SampleTimer {
public static void main(String[] args) {
System.out.println("I have set the task to run after 3 seconds.");
TimerTask task = new TimerTask() {
public void run() {
System.out.println("The task has been executed.");
}
};
Timer timer = new Timer();
timer.schedule(task, 3000);
}
}
After completing the above description, right-click SampleTimer.java> Run Java Application to execute it. It is OK if the message "The task has been executed" is output after 3 seconds.
console
I have set the task to run after 3 seconds.
The task has been executed.
I started my personal blog in 2020!
Based on the knowledge and experience gained as a freelance engineer, we plan to distribute content such as information on freelance engineers, IT technical information, industry information, and engineer life hacks.
The number of articles is still small, but it is updated weekly, so if you are interested, I would be grateful if you could take a look.
https://yacchi-engineer.com/
Recommended Posts