Schedule and Execute Task using Timer and TimerTask in Java
In this tutorial, I am sharing simple program snippet about, How to Schedule and Execute Task using Timer and TimerTask in Java. The program has been tested with environment and shared in the post.
MyTask.java
package com.dineshkrish.utilities; import java.util.TimerTask; public class MyTask extends TimerTask { @Override public void run() { // The task should go here... for (int i = 1; i <= 10; i++) { System.out.println("Job " + i); } } }
ScheduledTask.java
package com.dineshkrish.utilities; import java.util.Timer; public class ScheduledTask { // Method to get random wait time public static long getEstimatedWaitTime() { return (long)(Math.random() * 10000); } public static void main(String[] args) { // Defining Timer Object Timer timer = new Timer(); long waitTime = getEstimatedWaitTime(); System.out.println("Your Estimated Wait time is : "+(waitTime)+" mill seconds"); // Scheduling task timer.schedule(new MyTask(), waitTime); } }
Output
—————–
Your Estimated Wait time is : 7931 mill seconds
Job 1
Job 2
Job 3
Job 4
Job 5
Job 6
Job 7
Job 8
Job 9
Job 10
References
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet