Three ways to implement Java timed tasks

Source: Internet
Author: User
Tags java se

The translator notes: personal feel that using timed tasks to run garbage collection is not a very good example, from the translator's exposure to the project, the more common is to use timed tasks to perform non-real-time calculations, clear temporary data, files and so on.
In this article, I will give you 3 different ways to implement:
1. Common Thread implementations
2.TimerTask implementations
3.ScheduledExecutorService implementations

First, normal thread

This is the most common, create a thread, and then let it run in the while loop, through the sleep method to achieve the effect of a timed task. This can be implemented quickly and easily, with the following code:

Copy CodeThe code is as follows:
public class Task1 {
public static void Main (string[] args) {
Run in a second
Final long timeinterval = 1000;
Runnable Runnable = new Runnable () {
public void Run () {
while (true) {
-------code for task to run
SYSTEM.OUT.PRINTLN ("Hello!!");
-------ends here
try {
Thread.Sleep (timeinterval);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
};
Thread thread = new Thread (runnable);
Thread.Start ();
}
}

Second, with the timer and TimerTask

The above implementation is very fast and easy, but it also lacks some features.
The following are the advantages of using a timer and a timertask, compared with the above methods:

1. You can control when you start and cancel tasks
2. You can specify the delay time you want when you perform the task for the first time

When implemented, the timer class can dispatch tasks, timertask by implementing specific tasks in the run () method.
A timer instance can dispatch multiple tasks, which are thread-safe.
When the timer's constructor is called, it creates a thread that can be used to dispatch the task.
Here's the code:

Copy CodeThe code is as follows:
Import Java.util.Timer;
Import Java.util.TimerTask;
public class Task2 {
public static void Main (string[] args) {
TimerTask task = new TimerTask () {
@Override
public void Run () {
Task to run goes here
SYSTEM.OUT.PRINTLN ("Hello!!!");
}
};
Timer timer = new timer ();
Long delay = 0;
Long Intevalperiod = 1 * 1000;
Schedules the task to being run in an interval
Timer.scheduleatfixedrate (task, delay,
Intevalperiod);
}//End of Main
}


These classes exist starting with JDK 1.3.

Third, Scheduledexecutorservice

Scheduledexecutorservice is from the Java SE 5 java.util.concurrent, as a concurrent tool class was introduced, this is the most ideal timing task implementation.
Compared to the last two methods, it has the following benefits:

1. Compared to a single thread of a timer, it is a thread pool that performs the task
2. Can be very flexible to set the first time to execute the task delay
3. Provides a good convention to set the time interval for execution

Here is the implementation code, we show this example through Scheduledexecutorservice#scheduleatfixedrate, through the control of the parameters in the code, the first execution adds delay time.

:
Import java.util.concurrent.Executors;
Import Java.util.concurrent.ScheduledExecutorService;
Import Java.util.concurrent.TimeUnit;
public class Task3 {
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 ();
Service.scheduleatfixedrate (runnable, 0, 1, timeunit.seconds);
}
}

Three ways to implement Java timed tasks

Related Article

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.