Timer Timer __java-concurrency

Source: Internet
Author: User
1. Overview

Perform specific tasks on a regular basis. 2. Classes and Methods 2.1Timer

Java.util.Timer

A timer corresponds to a thread. A timer can schedule multiple tasks. If a task has an exception, the timer thread may not work properly, and other tasks are implicated. It is generally used to schedule lightweight tasks.

Java.util.timer#schedule (java.util.TimerTask task, java.util.Date when)

Perform a task at a specific time.

Java.util.timer#scheduleatfixedrate (timertask task, Date when, long period)

A task is executed every period, starting at a specific time.


2.2 TimerTask

Java.util.TimerTask

Abstract class, which implements the Runnable interface.

Java.util.timertask#cancel ()

Cancels the timed task.

Note: Used TimerTask is like worn socks, no way to be timer dispatch. TimerTask, which have been schedule or cancel, belong to the used TimerTask.
3. Sample Code

Common steps to see below.

1. Create a Class A that inherits from the TimerTask class and rewrite the run () method.

2. Create a Timer object, call the schedule () method, and pass the object of the custom Class A as an argument.

Import Java.util.Timer;

Class Timertasktest extends TimerTask {
	@Override public
	void Run () {
		System.out.println ("3 seconds to say hi");
	}
}

public class Timerdemo {public
	static void Main (string[] args) {
		Timer timer = new timer ();
		void Java.util.Timer.schedule (timertask task, long delay, long period)
		//delay time after period () every Task.run time interval () The function time unit is millisecond
		timer.schedule (New Timertasktest (), 0, 3000)
	;
}
 * * * 3 seconds say hi 
 * 3 seconds once say hi * 
 3 seconds say hi * 
 3 seconds say hi
 *  ...
 */

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.