Executing Another Method After Few Second in Java

Hi I just want to write a simple code, sometimes we want to post delay executing a particular method after few seconds (mins or hours).

import java.util.Date;

public class RunTimer {
	public static void main(String[] args) {

		System.out.println("--- entering static void main " + new Date());

		new java.util.Timer().schedule(new java.util.TimerTask() {
			@Override
			public void run() {
				try {

					System.out.println("--- Run 5 seconds after static void main executed " + new Date());

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, 5000); // in milliseconds

	}
}

and the result is :

--- entering static void main Sun Aug 26 11:11:43 WIB 2018
--- Run 5 seconds after static void main executed Sun Aug 26 11:11:48 WIB 2018

One thought on “Executing Another Method After Few Second in Java

Leave a Reply