SpringBoot实现定时任务

本文介绍了如何在SpringBoot中配置定时任务,包括引入SpringBootStarter依赖,使用@Component或@Service注解标注定时任务类,以及在启动类上启用定时任务。示例代码展示了使用@Scheduled注解定义cron表达式执行任务的方法。同时,文章还详细解释了cron表达式的各个字段含义,并给出了多个示例,帮助理解不同场景下的定时设置。
摘要由CSDN通过智能技术生成

1、引包

pom 包里面只需要引入 Spring Boot Starter 包即可

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>
</dependencies>

2、创建定时任务

@Component注解或@Service注解标注在定时任务方法所在类上
@Scheduled注解标注在执行方法上

package com.example.springboot_demo.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduleTask {

    @Scheduled(cron = "0/4 * * * * *")
    public void sayHello(){
        System.out.println("-----------------------------------hello 20210607-------------------------------------------");
    }
}

3、开启定时任务

在启动类上面加上@EnableScheduling即可开启定时

@EnableScheduling
@SpringBootApplication
@MapperScan(basePackages = "com.example.springboot_demo.mapper")
public class SpringbootDemoApplication {

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

}
cron表达式:

second(), minute(分), hour(时), day of month(日), month(月), day of week(周几).

0 0/5 14,18 * * ? 每天14点整,和18点整,每隔5分钟执行一次

0 15 10 ? * 1-6 每个月的周一至周六10:15分执行一次

0 0 2 ? * 6L 每个月的最后一个周六凌晨2点执行一次

0 0 2 LW * ? 每个月的最后一个工作日凌晨2点执行一次

0 0 2-4 ? * 1#1 每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值