Posts

Showing posts with the label TimerTask

Java - How to run a task periodically

In this section, we will show you h ow 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 ++) { ...