Java - How to run a task periodically

In this section, we will show you how to run a task periodically in Java.

1. ScheduledTask.java

import java.util.TimerTask;
import java.util.Date;

// Create a class extends with TimerTask
public class ScheduledTask extends TimerTask {

// to display current time
Date now;

// Add your task here
public void run() {
// initialize date
now = new Date();
// Display current time
System.out.println("Time is :" + now);
}
}

2. Run Scheduler Task

A class to run above scheduler task.

import java.util.Timer;

//Main class
public class SchedulerMain {
public static void main(String args[])
throws InterruptedException {

// Instantiate Timer Object
Timer time = new Timer();
// Instantiate SheduledTask class
ScheduledTask st = new ScheduledTask();
// Create Repetitively task for every 2 secs
time.schedule(st, 0, 2000);

//for demo only.
for (int i = 0; i <= 5; i++) {
System.out.println("Execution in Main Thread...." + i);
Thread.sleep(2000);
if (i == 5) {
System.out.println("Application Terminates");
System.exit(0);
}
}
}
}

Console Output:
Time is :Fri Jan 20 23:13:15 IST 2023
Execution in Main Thread....0
Time is :Fri Jan 20 23:13:17 IST 2023
Execution in Main Thread....1
Time is :Fri Jan 20 23:13:19 IST 2023
Execution in Main Thread....2
Time is :Fri Jan 20 23:13:22 IST 2023
Execution in Main Thread....3
Time is :Fri Jan 20 23:13:24 IST 2023
Execution in Main Thread....4
Time is :Fri Jan 20 23:13:26 IST 2023
Execution in Main Thread....5
Time is :Fri Jan 20 23:13:28 IST 2023
Application Terminates

More...

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete