Timer--timer in Java

Source: Internet
Author: User

First, class 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 code example

  • Import  Java.util.Timer;
  • Import  Java.util.TimerTask;
  • Public class Reminder ... {  
  • Timer timer;
  • Public Reminder (int seconds) ... {  
  • Timer = New timer ();
  • Timer.schedule (new remindtask (), 0, seconds*); Use the Timer class to set a scheduled task, 0 refers to 0s to start execution, seconds*1000 means to execute once every seconds seconds
  • }
  • class Remindtask extends TimerTask ... {  
  • Public void run () ... {  
  • System.out.println ("Time ' s up!"   ); Tasks to be performed on a timed basis
  • Timer.cancel (); //terminate the timer thread   
  • }
  • }
  • Public static void main (String args[]) ... {  
  • System.out.println ("About to schedule task." )  );
  • New  Reminder (5);
  • System.out.println ("Task scheduled." )  );
  • }
  • }

    Note :

    Each timer corresponds only to a single thread;
    The timer does not guarantee that the task executes very precisely;
    The Timer class is thread-safe.

  • Timer--timer in Java

    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.