SpringBoot -- Schedule Tasks

Keywords: Java Spring Attribute JavaEE

Starting with Spring 3.1, the implementation of scheduled tasks in Spring has become unusually simple.First turn on support for scheduled tasks by configuring the class annotation @EnableScheduling, then annotate @Scheduled on the method of executing the collection task to declare that this is a scheduled task.

Spring supports a variety of scheduled tasks through @Scheduled, including cron, fixDelay, fixRate, and so on.

I. Scheduled Task Execution Class

package com.cenobitor.scheduler.taskscheduler;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class ScheduledTaskService {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)//1
    public void reportCurrentTime(){
        System.out.println("Execute every five seconds "+DATE_FORMAT.format(new Date()));
    }

    @Scheduled(cron = "0 02 22 ? * *")//
    public void fixTimeExecution(){
        System.out.println("At a specified time "+DATE_FORMAT.format(new Date())+"implement");
    }
}

1. Declare through @Sceduled that the method is a scheduled task and execute at regular intervals using the fixedRate property.

2. Use the cron attribute to execute at a specified time, in this case at 22:02 a day.

2. Operation

package com.cenobitor.scheduler;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class SchedulerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchedulerApplication.class, args);
    }
}

Use the @EnableScheduling annotation to turn on support for scheduled tasks.

Run result:

Execute 22:01:54 every five seconds
Execute 22:01:59 every five seconds
Executed at 22:02:00 a.m.
Execute 22:02:04 every five seconds

Note: Extracted from "The Subversion of JavaEE Development SpringBoot Actual".

Posted by wilzy on Fri, 14 Feb 2020 09:07:13 -0800