Java Basics-Timer Task timer

Source: Internet
Author: User
Tags stub

Java Basics-Timer Task timer

I. Introduction of the Timer

Java.util.Timer

Java.util.TimerTask

A timer is a timer class that can be configured for a specified scheduled task. The TimerTask class is a timed task class that implements the Runnable interface and is an abstract class, as follows:

Public abstract class TimerTask implements Runnable

You can implement your own scheduled tasks by inheriting the class.

Timer timer instances are constructed in several ways:

Timer ()

Creates a new timer.

Timer (Boolean Isdaemon)

Creates a new timer that specifies its associated thread to run as a daemon.

Timer (String name)

Creates a new timer whose associated thread has the specified name.

Timer (String name, Boolean Isdaemon)

Creates a new timer whose associated thread has the specified name and can be specified to run as a daemon.

Second, timer method timing execution method

1. Perform a task at a specific time, only once

 Public void Schedule (timertask task,date time)

2. Perform tasks after a certain time, only once

 Public void Schedule (timertask task,long delay)

3, specify the time of the first execution, and then repeat the execution according to the interval time

 Public void Schedule (timertask task,date firsttime,long period)

4, the first execution after a certain delay, and then according to the interval time, repeated execution

 Public void Schedule (timertask task,long delay,long period)

Parameters:

Delay: The number of milliseconds deferred execution, that is, the first execution after delay milliseconds

Period: time interval for repeated executions

5, after the first execution, the specific frequency of execution, and 3 the same

 Public void scheduleatfixedrate (timertask task,date firsttime,long period)

6, the first execution after delay milliseconds, followed by a specific frequency of execution

 Public void scheduleatfixedrate (timertask task,long delay,long period)

The difference between the method name schedule () and Scheduleatfixedrate ()

<1>schedule () method more focused on maintaining the stability of the interval time: guaranteed to be callable every period time
The <2>scheduleatfixedrate () method focuses more on maintaining the stability of the execution frequency: The frequency of multiple calls is approaching period time, and if the task execution time is greater than period, the next task is executed immediately after the task is executed

Timer logoff

Timer.cancel ();

Third, the case

1. Execution after a certain time

 Public void Schedule (timertask task,long delay)

Parameters:

Task is: Perform tasks

Delay: milliseconds of time

Meaning of the method:

Executes task tasks after delay milliseconds and executes only once.

Case:

Synchronize data after 1 minutes.

Synchronization tasks:

 Package Com.yank.framework.common; Import Java.util.TimerTask;  Public class extends timertask {    @Override    publicvoid  run () {        // TODO auto-generated Method stub        System.out.println ("Synchro data to other servers.") );            }}

Scheduled tasks:

 PackageCom.yank.framework.common;ImportJava.util.Timer;ImportJava.util.TimerTask; Public classSynchrotest { Public Static voidMain (string[] args) {//TODO auto-generated Method Stubtimertask Task=NewSynchrotimertask (); Timer Timer=NewTimer (); Timer.schedule (Task,1000); }}

2, Case 2: Eat by the point

First define the task of eating, make food, no hours to check, to the point of eating.

 PackageCom.yank.framework.common;Importjava.util.ArrayList;ImportJava.util.Calendar;Importjava.util.List;ImportJava.util.TimerTask;/** Regular Meals **/ Public classEattimertaskextendsTimerTask {//Meal Time    Private StaticList<integer>Eattimes; /** Static Initialization **/    Static{initeattimes (); }        /** Initiation of meal time **/    Private Static voidIniteattimes () {eattimes=NewArraylist<integer>(); Eattimes.add (8); Eattimes.add (12); Eattimes.add (18); }    /** Execution **/@Override Public voidrun () {//TODO auto-generated Method StubCalendar Calendar =calendar.getinstance (); System.out.println ("Check to see if there's a point to eat."); inthour =Calendar.get (Calendar.hour_of_day); if(Eattimes.contains (hour)) {System.out.println ("Hungry, eating ..."); }    }}

Timed Check execution:

 PackageCom.yank.framework.common;ImportJava.util.Calendar;Importjava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask; Public classEattimertasktest { Public Static voidMain (string[] arg) {TimerTask task=NewEattimertask (); Calendar Calendar=calendar.getinstance (); Date Firsttime=Calendar.gettime (); //interval: 1 hours        LongPeriod = 1000 * 60 * 60; //test time per minute//period = 1000 * 60; Timer Timer=NewTimer ();    Timer.schedule (Task, firsttime, period); }}

Java Basics-Timer Task timer

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.