First, Introduction
It is often useful in applications to run timed tasks in the background. For example, the network operator will be a monthly data on the statistics. In Java we can inherit the TimerTask class to implement timed tasks.
Second, notes
/*** Scheduled Tasks * 1. Inherit the subclass of TimerTask (runable) * 2. Rewrite the Run method * 3. Write your own business in the Run method * 4. Start a scheduled task with the method provided by the Timer class *@authorHutiger **/ Public classTimetaskextendsTimerTask {PrivateTimer timer; Privatetimertask task; Public Static voidMain (string[] args) {Timetask T=NewTimetask (); //T.start ();SimpleDateFormat Sddateformat =NewSimpleDateFormat ("Yyyy-mm-dd Hh:mm:ss"); Date date; Try{Date= Sddateformat.parse ("2016-09-23 15:32:00"); T.start (date); } Catch(ParseException e) {//TODO Auto-generated catch blockE.printstacktrace (); }} @Override Public voidrun () {//TODO Auto-generated method stubs } Public voidStart (date date) {if(Timer = =NULL) {Timer=NewTimer (); } if(Task = =NULL) {Task=NewMyTimer (); } timer.schedule (task, date); //start execution within a certain time after the program startsTimer.schedule (Task, 5000,1000); //If the set time is obsolete, it will run from the current timeTimer.schedule (Task, date,1000); //if the setting is obsolete, it will be executed from the setup time and the completedTimer.scheduleatfixedrate (Task, date, 1000); } Public voidStop () {if(Task! =NULL) {task.cancel (); } if(Timer! =NULL) {timer.cancel (); } Task=NULL; Timer=NULL; }}classMyTimerextendsTimerTask {@Override Public voidrun () {//TODO Auto-generated method stubsSystem.out.println ("Tasks scheduled for execution"); }}
Java Learning notes: Java timed tasks