Java Program To Run Something Every X Minutes
Chapter:
Miscellaneous
Last Updated:
22-04-2023 04:09:44 UTC
Program:
/* ............... START ............... */
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
int delay = 0; // delay for x minutes
int period = 5 * 60 * 1000; // repeat every x minutes
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// put your task here
System.out.println("Task performed on " + new java.util.Date());
}
}, delay, period);
}
}
/* ............... END ............... */
Notes:
-
In this example, we first define the delay and period between executions of the task. The delay is set to 0, which means the task will start executing immediately. The period is set to 5 minutes, but you can change this to any number of minutes you like by modifying the calculation in the period variable.
- Next, we create a new Timer object and schedule a TimerTask to run at a fixed rate using the scheduleAtFixedRate() method. The TimerTask is defined as an anonymous inner class that overrides the run() method. In this example, the run() method simply prints a message to the console indicating that the task has been performed, but you can replace this with any code you like.
- The scheduleAtFixedRate() method takes three arguments: the TimerTask to run, the delay before the first execution, and the period between executions. In this case, the delay is set to 0 and the period is set to the value of period that we defined earlier.
- When you run this program, the task defined in the run() method will be executed every x minutes as specified by the period variable. You can replace the print statement with any code that you want to execute repeatedly every x.
Tags
Java Program To Run Something Every X Minutes #Java schedule task until condition #Run thread every 5 seconds? (Java)