异步任务
在启动类中开启异步任务功能
@EnableAsync
@SpringBootApplication
public class SpringbootTestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTestApplication.class, args);
}
}
在需要异步的方法上添加@Async注解
@Async
public void test(){
try {
Thread.sleep(342l);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("运行了");
}
定时任务
-
开启定时功能
在启动类上配置
@EnableScheduling
注解,开启定时任务功能 -
在方法上添加
@Scheduled注解
注解需要添加cron表达式,进行设置时间
例如:@Scheduled(cron = "0 2 * * * ") //每天凌晨两点执行 -
cron表达式
计划任务,是任务在约定的时间执行已经计划好的工作,这是表面的意思。在Linux中,我们经常用到 cron 服务器来完成这项工作。cron服务器可以根据配置文件约定的时间来执行特定的任务。crontab文件的格式:M H D m d cmd. M: 分钟(0-59)。 H:小时(0-23)。 D:天(1-31)。 m: 月(1-12)。 d: 一星期内的天(0~7,0,7为星期天,6为星期六)。
-
其他用法
@Scheduled(fixedDelay = 5000) //上一次执行完毕时间点之后5秒再执行 //与 fixedDelay 意思相同,只是使用字符串的形式。唯一不同的是支持占位符 @Scheduled(fixedDelayString = "5000") //上一次执行完毕时间点之后5秒再执行 @Scheduled(fixedRate = 5000) //上一次开始执行时间点之后5秒再执行 @Scheduled(fixedRateString = "5000") //与 fixedRate 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。 @Scheduled(initialDelay=1000, fixedRate=5000) //第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次 @Scheduled(initialDelayString="1000", fixedRate=5000) //使用字符串的形式。唯一不同的是支持占位符。