Timer and TimerTask -Execute a task for every 5 seconds in JAVA

https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html

https://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html

 

package com.practice.thread;

import java.util.Timer;
import java.util.TimerTask;

public class TimerClass extends TimerTask{

@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(“——–START———–“);
SomeWork();
System.out.println(“————–END——–“);
}

private void SomeWork() {
System.out.println(“INSIDE LOGIC PROGERSSSSSS”);
}

public static void main(String[] args) {
TimerClass timerTask=new TimerClass();
//have cancel() ,run() and scheduledExecutionTime() to know the time of task execution

Timer timer=new Timer();
//Run as daemon thred,By default thread is not daemon
//uses FIFO
//By default it is Thread-safe
//It uses Object.wait(long) to schedule .

//timer.schedule(timerTask, 1000,5000);

timer.scheduleAtFixedRate(timerTask, 0, 5000);
//Schedules the specified task for execution at the specified time.
//If the time is in the past, the task is scheduled for immediate execution.

//timer.cancel();

}

}

 

——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–
——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–
——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–
——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–
——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–
——–START———–
INSIDE LOGIC PROGERSSSSSS
————–END——–

…………………………….

…………….continues………………….

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s