Code:
import java.util.Timer; import java.util.TimerTask; public class ScheduleTask { static Timer timer = new Timer(); static class MyTimeTask extends TimerTask { public void run() { System.out.println("Running Task"); timer.cancel(); } } public static void main(String[] args) { System.out.println("Before timer.schedule()"); // schedule task in 2 seconds timer.schedule(new MyTimeTask(),2000); System.out.println("After timer.schedule()"); } }
Output:
$ java ScheduleTask Before timer.schedule() After timer.schedule() Running Task