Monday, March 25, 2024

java Timer

A simple program to schedule sonething in the future.
import java.util.TimerTask;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Timer;

class HelloWorld {

	private static class MyTimerTask extends TimerTask {

		String someValue;

		MyTimerTask(String someValue) {
			this.someValue = someValue;
		}

		@Override
		public void run() {
			System.out.println("Timer run " + someValue);
		}
	}

	public static void main(String[] args) {

		HelloWorld me = new HelloWorld();
		LocalDateTime someTimeLater = LocalDateTime.now().plusSeconds(3);

		Date futureDate1 = Date.from(someTimeLater.atZone(ZoneId.systemDefault()).toInstant());

		System.out.println("Scheduling something to be run in future...");

		new Timer().schedule(new MyTimerTask("hello my friend"), futureDate1);

		System.out.println("going on with my life");

	}

}