构建一个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()));
}
}