Android Timer with TimerTask

Source: Internet
Author: User

I. Overview

A timer is a timer tool that is used to schedule a specified task in a background thread. It can schedule a task to execute once or repeatedly.
TimerTask an abstract class whose subclasses represent a task that can be scheduled by the timer.

Second, the Timer and timertask related operation

Timer function is realized by combining timer with TimerTask. The specific implementation process is as follows:

The first step is to get the Timer instantiation object

Timer timer= new timer ();

Step Two, instantiate the TimerTask object

timertask timertask = new TimerTask () {

Publicvoid Run () {

Doing something

}

  }

When instantiating a TimerTask object, you need to rewrite its run () method, and then add the specific actions that need to be performed in the body of the method. For example, output a word, send a message and so on.

Step three, start the timer

timer.schedule (timertask, delay, period);

This completes the process of creating and starting a timer, but in practice it may require some other means of operation.

because the parameters of the timer are modified at some point, such as Delay,period, during the course of the program's operation. In order to use the latest and correct data in a timely manner, the existing timer needs to be closed and re-created and started with the new parameters.

The first step is to cancel the timertask and delete it in the timer timer queue.

If(TimerTask = = null) {

TimerTask. Cancel();

Second Step, restart the timer

If(timertask! = null) {

TimerTask = new TimerTask(

public void Run() {

Do something

) ;

Timer.schedule(timetask,delay,period);

It is noteworthy that the Cancle () method is executed after the TimerTask, when restarting the timer, you must re-instantiate the TimerTask is OK, otherwise it will be reported "Java.lang.IllegalStateException: TimerTask is scheduled already"error. Each timer task TimerTask can only be placed once

Android Timer with TimerTask

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.