Java implementation timed tasks

Source: Internet
Author: User

Package schedule;

Import java.util.concurrent.Executors;
Import Java.util.concurrent.ScheduledExecutorService;
Import Java.util.concurrent.TimeUnit;

/**
*
*
* Scheduledexecutorservice is from the Java SE5 java.util.concurrent, as a concurrent tool class was introduced, this is the most ideal timing task implementation method.
* 1> is a thread pool way to perform tasks compared to a single thread of a timer
* 2> can be flexible to set the first time to execute a task delay
* 3> provides a good convention to set the time interval for execution
*
* Below is the implementation code, we show this example through Scheduledexecutorservice#scheduleatfixedrate, through the control of the parameters in the code, the first execution added delay time.
*
*
* @author SHM
*
*/
public class Task {
public static void Main (string[] args) {
Runnable Runnable = new Runnable () {
public void Run () {
Task to run goes here
SYSTEM.OUT.PRINTLN ("Hello!!");
}
};
Scheduledexecutorservice Service = Executors
. Newsinglethreadscheduledexecutor ();
The second parameter is the delay time for the first execution, and the third parameter is the time interval for the scheduled execution
Service.scheduleatfixedrate (runnable, 1, timeunit.seconds);
}
}

Java implementation 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.