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

相关推荐
毕设源码-朱学姐12 小时前
【开题答辩全过程】以 广州网红点打卡介绍网站为例,包含答辩的问题和答案
java·eclipse
程序定小飞13 小时前
基于springboot的web的音乐网站开发与设计
java·前端·数据库·vue.js·spring boot·后端·spring
Hello_WOAIAI13 小时前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python
搬山.摧城13 小时前
线程池和单例模式
开发语言·单例模式
百锦再13 小时前
第1章 Rust语言概述
java·开发语言·人工智能·python·rust·go·1024程序员节
武昌库里写JAVA13 小时前
element-ui 2.x 及 vxe-table 2.x 使用 css 定制主题
java·vue.js·spring boot·sql·学习
一叶之秋141213 小时前
QT背景介绍与环境搭建
开发语言·qt
java1234_小锋13 小时前
PyTorch2 Python深度学习 - 模型保存与加载
开发语言·python·深度学习·pytorch2
JavaGuide14 小时前
OPPO 后端校招面试,过于简单了!
java·后端
码割机14 小时前
Linux服务器安装jdk和maven详解
java·linux·maven