Java Learning notes: Java timed tasks

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.