1. Schedule(timertask task, date time): Starts execution of the Run method in TimerTask on the specified date date
2. Scheduledelay): After a period of delay, start executing the Run method in TimerTask
3. Scheduledelay, long period): After a period of delay, start executing the Run method in TimerTask, and repeat the Run method after every period seconds
1 and 2 Examples:
Package Com.timer;import Java.util.date;import Java.util.timer;import Java.util.timertask;public class Run1 {private Static Timer timer = new timer ();/* TimerTask implementation class, and override the Run () method */static public class MyTask extends timertask{@Overridepu Blic void Run () {System.out.println ("ran! Time is: "+ new Date ());}} public static void Main (string[] args) {try{mytask task = new MyTask ();//timer.schedule (task, 5000);//After 5 seconds delay, Start executing the Run () method in the Task Timer.schedule (task, 5000, 2000);//After 5 seconds of delay, start executing the Run () method in the task and repeat the run () method every two seconds later}catch (Exception E ) {e.printstacktrace ();}}}
3 Examples:
Package Com.timer;import Java.text.simpledateformat;import Java.util.date;import java.util.timer;import Java.util.timertask;public class Run1 {private static timer timer = new timer (),/* * TimerTask implementation class, and override the Run () method */static Pu Blic class MyTask extends timertask{@Overridepublic void Run () {System.out.println ("ran! Time is: "+ new Date ());}} public static void Main (string[] args) {try{mytask task = new MyTask (); SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String datestring = "2017-10-17 9:45:00";D ate dateref = Sdf.parse (datestring); System.out.println ("String time:" + dateref.tolocalestring () + " Current time:" + new Date (). toLocaleString ()); Timer.schedule ( task, dateref);//start executing the Run () method on the specified date, the specified date is later than your current system time}catch (Exception e) {e.printstacktrace ();}}}
Run effect
String time:£ º9: Current time:10 -9:: £ º xx .
Java Timer: Timer