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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>