Table of Contents
Timing task framework
TimeTask
ScheduledExecutorService
Spring Task
Home Java javaTutorial How to implement scheduled tasks in Java stand-alone environment

How to implement scheduled tasks in Java stand-alone environment

Apr 18, 2023 pm 12:16 PM
java

Timing task framework

How to implement scheduled tasks in Java stand-alone environment

TimeTask

Since we started learning java, the first time to implement scheduled tasks was to use TimeTask, and Timer was used internally The TaskQueue class stores scheduled tasks. It is a priority queue based on a minimum heap implementation. TaskQueue will sort the tasks according to the distance between the tasks and the next execution time, ensuring that the tasks on the top of the heap are executed first.

Example code:

 public static void main(String[] args)
    {
          TimerTask task = new TimerTask() {
              public void run() {
                  System.out.println("当前时间: " + new Date() + "n" +
                          "线程名称: " + Thread.currentThread().getName());
              }
          };
          Timer timer = new Timer("Timer");
          long delay = 5000L;
          timer.schedule(task, delay);
          System.out.println("当前时间: " + new Date() + "n" +
                  "线程名称: " + Thread.currentThread().getName());
    }
Copy after login

Running result:

当前时间: Wed Apr 06 22:05:04 CST 2022n线程名称: main
当前时间: Wed Apr 06 22:05:09 CST 2022n线程名称: Timer
Copy after login

As can be seen from the result, the scheduled task was executed after 5 seconds.

Disadvantages:

  • TimeTask execution tasks can only be executed serially. Once one task takes a long time to execute, it will affect the execution of other tasks.

  • If an exception occurs during task execution, the task will stop directly.

As time goes by, java technology is constantly updated. In response to the shortcomings of TimeTask, ScheduledExecutorService appears to replace TimeTask.

ScheduledExecutorService

ScheduledExecutorService is an interface with multiple implementation classes. The more commonly used one is ScheduledThreadPoolExecutor. The ScheduledThreadPoolExecutor itself is a thread pool, which uses DelayQueue internally as a task queue and supports concurrent execution of tasks.

Example code:

 public static void main(String[] args) throws InterruptedException
   {
      ScheduledExecutorService executorService =
              Executors.newScheduledThreadPool(3);
      // 执行任务: 每 10秒执行一次
      executorService.scheduleAtFixedRate(() -> {
          System.out.println("执行任务:" + new Date()+",线程名称: " + Thread.currentThread().getName());
      }, 1, 10, TimeUnit.SECONDS);
    }
Copy after login

Disadvantages:

  • Try to avoid using Executors to create threads Pool, because the queue used internally in the thread pool of jdk is relatively large, it is easy for OOM to occur.

  • Scheduled tasks are based on JVM stand-alone memory. Once the scheduled task is restarted, it disappears.

  • Cannot support cron expressions to implement rich scheduled tasks.

Spring Task

After learning Spring, I started using Spring’s own Task. Spring Framework comes with scheduled tasks and provides cron expressions to implement rich scheduled task configurations.

Instance code:

@EnableScheduling
@Component
public class SpringTask
{
    private Logger logger = LoggerFactory.getLogger(SpringTask.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
            "HH:mm:ss");
    /**
     * fixedRate:固定速率执行。每5秒执行一次。
     */
    @Scheduled(fixedRate = 5000)
    public void invokeTaskWithFixedRate()
    {
        logger.info("Fixed Rate Task :  Current Time  is  {}",
                dateFormat.format(new Date()));
    }
    /**
     * fixedDelay:固定延迟执行。距离上一次调用成功后2秒才执。
     */
    @Scheduled(fixedDelay = 2000)
    public void invokeTaskWithFixedDelay()
    {
        try
        {
            TimeUnit.SECONDS.sleep(3);
            logger.info("Fixed Delay Task : Current Time  is  {}",
                    dateFormat.format(new Date()));
        }
        catch (InterruptedException e)
        {
            logger.error("invoke task error",e);
        }
    }
    /**
     * initialDelay:初始延迟。任务的第一次执行将延迟5秒,然后将以5秒的固定间隔执行。
     */
    @Scheduled(initialDelay = 5000, fixedRate = 5000)
    public void invokeTaskWithInitialDelay()
    {
        logger.info("Task with Initial Delay : Current Time is  {}",
                dateFormat.format(new Date()));
    }
    /**
     * cron:使用Cron表达式,每隔5秒执行一次
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void invokeTaskWithCronExpression()
    {
        logger.info("Task Cron Expression:  Current Time  is  {}",
                dateFormat.format(new Date()));
    }
}
Copy after login

Execution result:

2022-04-06 23:06:20.945 INFO 14604 --- [ scheduling-1] com.fw.task.SpringTask : Task Cron Expression: Current Time is 23:06:20
2022-04-06 23:06:22.557 INFO 14604 --- [ scheduling -1] com.fw.task.SpringTask : Task with Initial Delay : Current Time is 23:06:22
2022-04-06 23:06:22.557 INFO 14604 --- [ scheduling-1] com.fw .task.SpringTask : Fixed Rate Task : Current Time is 23:06:22
2022-04-06 23:06:25.955 INFO 14604 --- [ scheduling-1] com.fw.task.SpringTask : Fixed Delay Task : Current Time is 23:06:25
2022-04-06 23:06:25.955 INFO 14604 --- [ scheduling-1] com.fw.task.SpringTask : Task Cron Expression: Current Time is 23: 06:25
2022-04-06 23:06:27.555 INFO 14604 --- [ scheduling-1] com.fw.task.SpringTask : Task with Initial Delay : Current Time is 23:06:27
2022-04-06 23:06:27.556 INFO 14604 --- [ scheduling-1] com.fw.task.SpringTask : Fixed Rate Task : Current Time is 23:06:27

@ EnableScheduling needs to enable scheduled tasks, and @Scheduled(cron = "0/5 * * * * ?") configures the rules for scheduled tasks. The cron expression supports rich scheduled task configurations. If you are not familiar with it, you can check out

Advantages:

It is simple and convenient to use and supports various complex scheduled task configurations

Disadvantages:

  • Based on stand-alone scheduled tasks, the scheduled tasks will disappear once restarted.

  • The scheduled task defaults to a single-threaded execution task. If parallel execution is required, @EnableAsync must be turned on.

  • Without unified graphical task scheduling management, scheduled tasks cannot be controlled

The above is the detailed content of How to implement scheduled tasks in Java stand-alone environment. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles