Java - SpringBoot - 2.x - 任务管理 - 定时 - 使用Spring 的 Scheduled实现定时任务

参考

特点

  • 默认单线程执行任务,多任务阻塞运行

使用

1、启动类使用@EnableScheduling注解开启定时任务

@SpringBootApplication
@EnableScheduling
public class ScheduledTest {
    public static void main(String[] args) {
        SpringApplication.run(ScheduledTest.class);
    }
}

2.2、添加定时任务(2种方式)

方式一:使用@Scheduled注解

@Slf4j
@Component
public class ScheduledTasks {

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

    @Scheduled(cron = "0/2 * * * * ? ")
    public void task1() {
        log.info("定时任务1,每2秒执行一次,time: {}", dateFormat.format(new Date()) + " 线程:" + Thread.currentThread().getName());
    }
}

方式二:实现SchedulingConfigurer接口

@Configuration
@Component
@Slf4j
public class TestTask implements SchedulingConfigurer {

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

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addFixedDelayTask(this::index2, 1000);
    }

    public void index2() {
        log.info("定时任务2,每1秒执行一次,time:" + dateFormat.format(new Date()) + " 线程:" + Thread.currentThread().getName());
    }
}

思考与进阶

多处部署的问题:每处都会执行一次定时任务。
考虑使用支持分布式的定时任务实现。

posted @ 2022-04-09 09:45  阿明,小明  阅读(99)  评论(0编辑  收藏  举报