Spring定时任务实现方法— @Scheduled注解、实现SchedulingConfigurer接口

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() 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值