Home >Java >javaTutorial >How to implement scheduled tasks in Java stand-alone environment

How to implement scheduled tasks in Java stand-alone environment

王林
王林forward
2023-04-18 12:16:031342browse

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());
    }

Running result:

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

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);
    }

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()));
    }
}

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:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete