Three implementation methods of Java timed task _java

Source: Internet
Author: User
Tags garbage collection time interval java se

Translator Note: Personally feel that the use of timed tasks to run garbage collection is not a good example, from the translator's exposure to the project, it is more common to use timed tasks to perform non-real time calculations, to clear temporary data, documents and so on.
In this article, I'll introduce you to 3 different implementations:
1. General Thread Implementation
2.TimerTask implementation
3.ScheduledExecutorService implementation

First, General 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 timed tasks. This can be quickly and easily implemented with the following code:

Copy Code code 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 timer and TimerTask

The implementation above is very quick and easy, but it lacks some functionality.
The use of timer and timertask in comparison with the above methods has the following advantages:

1. Can control when starting and canceling tasks
2. The first time you perform a task, you can specify the delay time you want.

When implemented, the timer class can schedule tasks, and timertask to implement specific tasks in the run () method.
A timer instance can schedule multiple tasks, which is thread-safe.
When the timer's constructor is invoked, it creates a thread that can be used to schedule tasks.
Here's the code:

Copy Code code 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
SYSTEM.OUT.PRINTLN ("Hello!!!");
}
};
Timer timer = new timer ();
Long delay = 0;
Long Intevalperiod = 1 * 1000;
Schedules the task to is run in an interval
Timer.scheduleatfixedrate (task, delay,
Intevalperiod);
}//End of Main
}

These classes begin to exist from JDK 1.3.

Third, Scheduledexecutorservice

Scheduledexecutorservice is introduced from the Java SE 5 java.util.concurrent as a concurrency tool class, which is the ideal way to implement a timed task.
Compared to the last two methods, it has the following benefits:

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

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

Copy Code code as follows:

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
SYSTEM.OUT.PRINTLN ("Hello!!");
}
};
Scheduledexecutorservice Service = Executors
. Newsinglethreadscheduledexecutor ();
Service.scheduleatfixedrate (runnable, 0, 1, timeunit.seconds);
}
}

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.