[Java Basics] 32 Timing Scheduling


In software development, scheduled tasks are a common requirement for executing specific tasks or operations periodically. Java provides two main timing scheduling methods: Timer Class sum ScheduledExecutorService interface.

Timer class

Create Timer

Timerclass is a simple timing scheduling tool provided by Java. It allows you to schedule a task to be executed at some point in the future, or to be executed repeatedly at fixed intervals.

Sample code:

import java.time.LocalTime;
import java.util.Timer;
import java.util.TimerTask;
public class Demo {
    
    
    public static void main(String[] args) {
    
    
        Timer timer = new Timer();

        // 创建一个定时任务,延迟 2000 毫秒后开始执行,每隔 5000 毫秒执行一次
        timer.schedule(new TimerTaskDemo(), 2000, 5000);
    }
}

class TimerTaskDemo extends TimerTask {
    
    
    @Override
    public void run() {
    
    
        System.out.println("执行任务: " + LocalTime.now());
    }
}

Output result:

Insert image description here

Precautions

  • TimerThe class is single-threaded when executing tasks. If the execution time of one task is too long, it will affect the execution of other tasks.

  • If a task throws an uncaught exception during execution, then Timer will terminate all scheduled tasks.

ScheduledExecutorService interface

ScheduledExecutorServiceIt is a more powerful and flexible timing scheduling tool provided by Java. It is implemented based on a thread pool, allowing multiple tasks to be executed simultaneously and providing more scheduling options.

Create ScheduledExecutorService

Sample code:

import java.time.LocalTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

        // 创建一个定时任务,延迟 2 秒后开始执行,每隔 5 秒执行一次
        executorService.scheduleAtFixedRate(
                () -> System.out.println("执行任务: " +  LocalTime.now()),
                2, 5, TimeUnit.SECONDS
        );
    }
}

Output result:

Insert image description here

Precautions

  • ScheduledExecutorServiceUsing a thread pool, it can better handle the concurrent execution of multiple scheduled tasks.
  • It provides more flexible scheduling options. For example, you can set the delay time for the first execution, and you can also determine the start time of the next task based on the execution completion time of the previous task.

Choose the appropriate timing scheduling method

Applicable scenarios for Timer

  • For simple scheduled tasks and the task execution time is short, you can choose to use Timer.
  • Suitable for single-threaded execution scenarios that do not involve a large number of concurrent tasks.

Applicable scenarios for ScheduledExecutorService

  • Suitable for complex scheduled task scenarios, with more scheduling options and more flexible execution methods.

  • When multiple scheduled tasks need to be processed, ScheduledExecutorService is more suitable because it is based on the thread pool and can better handle concurrent tasks.

Summarize

Java provides two main timing scheduling methods: Timer and ScheduledExecutorService. Choosing the appropriate scheduling method depends on the specific needs of your project. For simple scheduled tasks, Timer can meet the needs. For more complex and flexible scenarios, and situations where multiple scheduled tasks need to be processed, it is recommended to use ScheduledExecutorService. In actual projects, choosing an appropriate timing scheduling method based on the nature and complexity of the task is an important factor in improving system performance and stability.

Guess you like

Origin blog.csdn.net/yanyc0411/article/details/134959675