Spring定时任务实现方法
文章目录
前言
我们了解到xxl-job是一个轻量级分布式任务调度平台,可以作为调度中心来使用,当然它也是一个独立的springboot服务,如果我们有大量的调度任务可以考虑引入;今天我们要讨论的是假设我的java项目中就只有个别业务场景需要简单使用一下定时任务,这个时候引入xxl-job就有点太重了,我们使用spring定义的Scheduled注解以及使用配置类实现SchedulingConfigurer接口来实现定时任务。
一、使用@Scheduled注解
1.在Spring配置类上添加@EnableScheduling注解来启用定时任务;
2.使用@Component注解,表示将此类标记为Spring容器中的一个Bean;
3.创建定时任务方法,并使用@Scheduled注解来指定任务的执行计划。
demo代码如下:
package com.aaa.sasacdataboard.config;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @Author:
* @Date:2024/8/16 9:59
*/
@EnableScheduling
//@Component
public class ScheduledTasks {
//1.上一个任务结束到下一个任务开始的时间间隔为固定的3秒,任务的执行总是要先等到上一个任务的执行结束
@Scheduled(fixedDelay = 3000)
public void printCurrentTimeByDelay() {
System.out.println("前后两个任务间隔3s打印一下当前时间:" + System.currentTimeMillis());
}
@Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds:10000}")
public void outputCurrentTimeByDelay()