SpringBoot 实现定时任务

本文指导如何在SpringBoot项目中无需外部依赖,通过@EnableAsync和@EnableScheduling启用定时任务与异步功能,示例了固定速率和cron表达式的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

构建一个SpringBoot 项目,无需添加任何依赖(自动会给你添加),然后直接上代码:

package com.miaoqiang;

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

import java.text.DateFormat;
import java.util.Date;

/**
 * @EnableScheduling //开启定时任务
 * @Scheduled(fixedRate = 5000) 5秒执行一次
 * cron表达式语法
 *[秒] [分] [小时] [日] [月] [周] [年]   注意:[年] 只有springboot中才有 spring中是没有的
 * 1	秒	是	0-59	, - * /
 * 2	分	是	0-59	, - * /
 * 3	时	是	0-23	, - * /
 * 4	日	是	1-31	, - * ? / L W
 * 5	月	是	1-12 / JAN-DEC	, - * /
 * 6	周	是	1-7 or SUN-SAT	, - * ? / L #
 * 7	年	否	1970-2099	, - * /
 *  * :表示所有值 ? :表示不指定值  经常用在 月 与 周  - :表示区间  , :表示指定多个值
 *  / :用于递增触发  L :表示最后的意思  W :表示离指定日期的最近那个工作日
 *  # :序号(表示每月的第几个周几)
 * 额外注意下,周   数字  4 代表周三  因为外国人是以 周日 作为 一周的第一天
 * 定时任务执行默认是单线程模式,会创建一个本地线程池,线程池大小为1。当项目中有多个定时任务时,任务之间会相互等待,同步执行
 * 可以开启异步注解 @EnableAsync  然后在具体方法上加上 @Async
 */
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class SpringbootScheduleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootScheduleApplication.class, args);
    }
    @Async
    @Scheduled(fixedRate = 5000)
    public void doSomething(){
        System.out.println("我的定时任务: fixedRate" + "线程名称:" + Thread.currentThread().getName() + "时间:" +  DateFormat.getInstance().format(new Date()));
    }
    @Async
    @Scheduled(cron = "*/2 * * * * ?")
    public void doOtherThing(){
        System.out.println("我的定时任务: corn表达式" +  "线程名称:" + Thread.currentThread().getName() + "时间:" +  DateFormat.getInstance().format(new Date()));
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值