Three methods for implementing scheduled tasks in Java

Source: Internet
Author: User

The three methods for Java to implement scheduled tasks are often used in applications to run scheduled tasks in the background. For example, you need to run a scheduled task in the backend of the service for garbage collection, from the project exposed by the translator, it is common to use scheduled tasks for non-real-time computing and clearing temporary data and files ).

In this article, I will introduce three different implementation methods:

  • General thread implementation
  • TimerTask implementation
  • ScheduledExecutorService implements common thread

    This is the most common practice. Create a thread and keep it running in the while loop. The sleep method is used to achieve the effect of scheduled tasks. The Code is as follows:

    12345678910111213141516171819202122 public class Task1 {public static void main(String[] args) { // run in a second finallong timeInterval = 1000; Runnable runnable =new Runnable() { publicvoid 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(); }}

    Use Timer and TimerTask

    The above implementation is very fast and simple, but it also lacks some features.
    Using Timer and TimerTask has the following advantages over the above methods:

    • It can be controlled when the task is started and canceled
    • You can specify the desired delay time for the first task execution.

      During implementation, the Timer class can schedule tasks, while the TimerTask class implements specific tasks in the run () method.
      A Timer instance can schedule multiple tasks, which are thread-safe.
      When the Timer constructor is called, it creates a thread that can be used to schedule tasks.
      The following code is used:

      12345678910111213141516171819 import java.util.Timer;import java.util.TimerTask;public class Task2 { publicstatic void main(String[] args) { TimerTask task =new TimerTask() { @Override publicvoid run() { // task to run goes here System.out.println("Hello !!!"); } }; Timer timer =new Timer(); longdelay = 0; longintevalPeriod = 1* 1000; // schedules the task to be run in an interval timer.scheduleAtFixedRate(task, delay, intevalPeriod); }// end of main}

      These classes exist from JDK 1.3.

      ScheduledExecutorService

      ScheduledExecutorService is introduced from Java. util. concurrent of java SE 5 as a concurrency tool class, which is the best implementation method for scheduled tasks.
      Compared with the above two methods, it has the following benefits:

      • Compared with the single thread of Timer, it executes tasks through the thread pool.
      • You can flexibly set the delay time for the first task execution.
      • Provides good conventions to set the execution Interval

        The following is the implementation code. We use ScheduledExecutorService # scheduleAtFixedRate to demonstrate this example. Through the control of parameters in the Code, the first execution adds the delay time.

        12345678910111213141516 import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class Task3 { publicstatic void main(String[] args) { Runnable runnable =new Runnable() { publicvoid run() { // task to run goes here System.out.println("Hello !!"); } }; ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(runnable,0, 1, TimeUnit.SECONDS); }}

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.