java-SpringBoot执行定时任务-任务调度-@EnableScheduling和@Scheduled

文章目录

java借助springBoot框架,执行定时任务

0. 项目地址

https://github.com/OrangeHza/JavaDemo

1. 需求分析

可能有一些需要定时执行的任务,如:

  • 每隔2s执行一次
  • 每天凌晨3点30分执行一次
  • 每周一凌晨0点执行一次

通过springBoot框架很容易实现

注意方法只能是空参和无返回值的方法

2、新建springBoot项目



删掉多余的目录,最终结构如下:

新建了一个类:TaskService

3. 编写定时任务

3.1 开启调度任务

引导类加注解:@EnableScheduling

java 复制代码
package cn.whu.schedule;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling // 开启调度任务 定时执行Bean中被@Scheduled修饰的方法(定时任务)
public class ScheduleApplication {

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

}

3.2 编写定时任务方法

注意必须是空参无返回值的方法,需要传递参数需要自己建域了,如:静态对象、静态成员

java 复制代码
package cn.whu.schedule.service;

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

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;


@Service
public class TaskService {

    @Scheduled(fixedDelay = 2000) // 每隔2s执行一次
    public void task01() {
        System.out.println("每2秒执行一次的任务:  " + nowTime());
    }

    // cron 表达式格式为 秒 分 时 日 月 星期 年,支持通配符和特定值设置。
    @Scheduled(cron = "0 30 3 * * ?") // 每天凌晨3点30分执行一次
    public void task02() {
        // 执行任务逻辑
        System.out.println("每天凌晨3点30分执行的任务: " + nowTime());
    }

    // cron 表达式格式为 秒 分 时 日 月 星期 年,支持通配符和特定值设置。
    @Scheduled(cron = "0 0 0 ? * MON") // 每周一凌晨0点执行任务   ?指的是哪天都行
    public void task03() {
        // 执行任务逻辑
        System.out.println("每周一执行的任务: " + nowTime());
    }


    public String nowTime() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 定义格式化模板
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EEEE", Locale.CHINESE);
        // 格式化当前时间
        String formattedDateTime = now.format(formatter);
        // 输出格式化后的时间
        return formattedDateTime;
    }
}

启动引导类ScheduleApplication的main方法,可以看到控制台打印:

成功,boot就是强大

相关推荐
南山十一少1 小时前
Spring Security+JWT+Redis实现项目级前后端分离认证授权
java·spring·bootstrap
软件黑马王子3 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
闲猫3 小时前
go orm GORM
开发语言·后端·golang
427724003 小时前
IDEA使用git不提示账号密码登录,而是输入token问题解决
java·git·intellij-idea
chengooooooo3 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
李长渊哦3 小时前
常用的 JVM 参数:配置与优化指南
java·jvm
计算机小白一个3 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
Tirzano4 小时前
springsecurity自定义认证
spring boot·spring
李白同学4 小时前
【C语言】结构体内存对齐问题
c语言·开发语言
黑子哥呢?5 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash