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就是强大

相关推荐
再见晴天*_*44 分钟前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
lqjun08272 小时前
Qt程序单独运行报错问题
开发语言·qt
hdsoft_huge4 小时前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
风中的微尘4 小时前
39.网络流入门
开发语言·网络·c++·算法
雨白5 小时前
Java 多线程指南:从基础用法到线程安全
android·java
Hungry_Shark5 小时前
IDEA版本控制管理之使用Gitee
java·gitee·intellij-idea
赛姐在努力.5 小时前
《IDEA 突然“三无”?三秒找回消失的绿色启动键、主菜单和项目树!》
java·intellij-idea
未来之窗软件服务5 小时前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
猎板PCB黄浩5 小时前
从废料到碳减排:猎板 PCB 埋容埋阻的绿色制造革命,如何实现环保与性能双赢
java·服务器·制造
ZzzK,5 小时前
JAVA虚拟机(JVM)
java·linux·jvm