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

相关推荐
TomCode先生2 小时前
c#动态树形表达式详解
开发语言·c#
高-老师2 小时前
基于R语言的物种气候生态位动态量化与分布特征模拟
开发语言·r语言·物种气候
大翻哥哥3 小时前
Python 2025:量化金融与智能交易的新纪元
开发语言·python·金融
weixin_437830943 小时前
使用冰狐智能辅助实现图形列表自动点击:OCR与HID技术详解
开发语言·javascript·ocr
鹿鹿学长4 小时前
2025年全国大学生数学建模竞赛(C题) 建模解析|婴儿染色体数学建模|小鹿学长带队指引全代码文章与思路
c语言·开发语言·数学建模
zhousenshan4 小时前
Python爬虫常用框架
开发语言·爬虫·python
皮皮林5514 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
weixin_456904275 小时前
Spring Boot 用户管理系统
java·spring boot·后端
趁你还年轻_5 小时前
异步编程CompletionService
java
DKPT5 小时前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习