I. Overview
In Java implementation of the function of timed tasks, mainly used in two classes, timer and TimerTask class. Where the timer is used to perform the specified task on a background thread according to the specified schedule.
TimerTask an abstract class whose subclasses represent a task that can be scheduled by the timer, and the code to execute is written in the Run method that TimerTask needs to be implemented.
Second, first look at one of the simplest examples
We use code to illustrate
ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask; Public classTimerdemo { Public StaticString GetCurrentTime () {Date Date=NewDate (); SimpleDateFormat SDF=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); returnSdf.format (date); } Public Static voidMain (string[] args)throwsinterruptedexception {System.out.println ("Main start:" +getcurrenttime ()); Starttimer (); Thread.Sleep (1000*5);//Sleep 5 SecondsSystem.out.println ("Main end:" +getcurrenttime ()); } Public Static voidStarttimer () {timertask task=NewTimerTask () {@Override Public voidrun () {System.out.println ("Task run:" +getcurrenttime ()); } }; Timer Timer=NewTimer (); Timer.schedule (Task,0); }}
In order to facilitate the printing of observation information, we add some printing information in the main method, and call Thread.Sleep to let the main thread sleep a bit. In addition, a getcurrenttime method that gets the current date is added to the class. When we run the above code, we find that the program immediately prints information similar to the following:
Main START:2016-01-13 22:23:18
Task Run:2016-01-13 22:23:18
Java: Using the Java Timer class to implement the functions of timed tasks