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

相关推荐
S***26752 小时前
基于SpringBoot和Leaflet的行政区划地图掩膜效果实战
java·spring boot·后端
汤姆yu2 小时前
基于python的外卖配送及数据分析系统
开发语言·python·外卖分析
Yue丶越2 小时前
【C语言】字符函数和字符串函数
c语言·开发语言·算法
马剑威(威哥爱编程)2 小时前
鸿蒙6开发视频播放器的屏幕方向适配问题
java·音视频·harmonyos
JIngJaneIL2 小时前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
翔云 OCR API2 小时前
人脸识别API开发者对接代码示例
开发语言·人工智能·python·计算机视觉·ocr
V***u4533 小时前
MS SQL Server partition by 函数实战二 编排考场人员
java·服务器·开发语言
这是程序猿3 小时前
基于java的ssm框架旅游在线平台
java·开发语言·spring boot·spring·旅游·旅游在线平台
芳草萋萋鹦鹉洲哦3 小时前
【elemen/js】阻塞UI线程导致的开关卡顿如何优化
开发语言·javascript·ui
爱学习的小邓同学3 小时前
C++ --- 多态
开发语言·c++