spring boot 定时任务(单线程)

本文介绍SpringBoot中定时任务的配置与实现方法,包括pom文件的依赖配置、启动类注解说明及定时任务具体实现代码示例。通过cron表达式的详细解析帮助读者更好地理解和应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring boot 中 pom 文件配置

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

spring boot 启动类

@SpringBootApplication
@EnableScheduling
public class DemoApplication {

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

    }

}

定时任务

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;

@Component
public class ScheduledService {

    private static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);

    //单线程定时任务
    @Scheduled(cron="0 0/1 * * * ?")
    public void one() {
        // 间隔2分钟,执行任务
        Thread current = Thread.currentThread();


        logger.info("ScheduledTest.executeFileDownLoadTask 定时任务1:"+current.getId()+ ",name:"+current.getName());
    }
    @Scheduled(cron="0 0/2 * * * ?")
    public void two() {
        // 间隔2分钟,执行任务
        Thread current = Thread.currentThread();


        logger.info("ScheduledTest.executeFileDownLoadTask 定时任务1:"+current.getId()+ ",name:"+current.getName());
    }
}

 

cron表达式详解

0 0/2 * * * ?

第一位:秒 取值范围(0-59)

第二位:分 取值范围(0-59)

第三位:时 取值范围(0-23)

第四位:天 取值范围(0-31)

第五位:月 取值范围(0-11)

第六位: 星期 取值范围(1-7 1=SUN MON TUE WED THU FRI SAT)

第七位:年份 (1970-2099)

一个cron表达式可以有七位也可以有六位

每一位都有三种表达方式

第一种:10(直接写一个值)假如是第一位(第一位代表秒),每分钟的第10秒运行。

第二种:0/10表示每10秒钟运行一次

第三种:0-10表示每分钟的0-10秒,每秒运行一次

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值