Java: Using the Java Timer class to implement the functions of timed tasks

Source: Internet
Author: User

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

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.