Spring boot的定时任务调度

在做项目时有时候会有定时器任务的功能,比如某某时间应该做什么,多少秒应该怎么样之类的。

spring支持多种定时任务的实现。我们来介绍下使用spring的定时器和使用quartz定时器

  1.我们使用spring-boot作为基础框架,其理念为零配置文件,所有的配置都是基于注解和暴露bean的方式。

  2.使用spring的定时器:

    spring自带支持定时器的任务实现。其可通过简单配置来使用到简单的定时任务。

Spring boot的定时任务调度

在application.properties里面设置任务调度的间隔时间


Spring boot的定时任务调度


/**
 * @author jetlag
 * @email [email protected]
 * @description:从配置文件加载任务信息
 */
@Component
public class ScheduledTask {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedDelayString = "${jobs.fixedDelay}")
    public void getTask1() {
        System.out.println("任务1,当前时间:" + dateFormat.format(new Date()));
    }

    @Scheduled(cron = "${jobs.cron}")
    public void getTask2() {
        System.out.println("任务2,当前时间:" + dateFormat.format(new Date()));
    }
}

没了,没错,就是这么的简单,任务调度就完成了

这里注意了在启动类上还要加一个注解@EnableScheduling:标注启动定时任务。