您当前的位置: 首页 >  spring

星夜孤帆

暂无认证

  • 2浏览

    0关注

    626博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringBoot定时任务

星夜孤帆 发布时间:2020-11-20 17:38:22 ,浏览量:2

一、定时任务 1.1 简介

项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor、 TaskScheduler接口。

两个注解:@EnableScheduling、@Scheduled

cron表达式

1.2 代码示例 1.2.1 启动类

启动类标注@EnableScheduling注解开启基于注解的定时任务

package com.best;

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

@EnableScheduling //开启基于注解的定时任务
@SpringBootApplication
public class ScheduleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication.class, args);
    }
}
1.2.2 业务类

需要定时的方法上面,标注@Scheduled注解,并配置cron表达式,来指示什么时候执行

package com.best.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledService {

    /**
     * second(秒), minute(分), hour(时), day(日), month(月), week(周)
     * 0 * * * * MON-FRI
     */
//    @Scheduled(cron = "* * * * * *")//任意一秒
//    @Scheduled(cron = "0,1,2,3 * * * * MON-SAT") //周一到周六不管哪一天哪一分,0,1,2,3秒都会执行一次
//    @Scheduled(cron = "0-3 * * * * MON-SAT") //周一到周六不管哪一天哪一分,0-3秒都会执行一次
//    @Scheduled(cron = "0/3 * * * * MON-SAT") //从0秒开始每3s执行一次
    @Scheduled(cron = "0/3 * * 0 * ?") //日/星期冲突匹配,注意?中英文
    public void hello() {
        System.out.println("hello...");
    }

}
1.2.3 测试

源码

关注
打赏
1636984416
查看更多评论
立即登录/注册

微信扫码登录

0.0465s