静态:基于注解
基于注解@Scheduled默认为单线程,开启多个任务时,任务的执行时机会受上一个任务执行时间的影响。
1.创建定时任务
使用SpringBoot基于注解来创建定时任务非常简单,只需几行代码便可完成。 代码如下:
package com.hnbd.dome.timing;
import com.hnbd.dome.service.ForestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* 定时任务
*
* @创建人 江枫沐雪
* @创建时间 2021/6/11 15:48
*/
@Configuration //1.主要用于标记配置类
@EnableScheduling //2.开启定时任务
public class ForestTiming {
@Autowired
private ForestService forestService;
/**
* 指定时间执行任务 cron的时间格式 从零秒开始,每五秒执行一次
* @Scheduled(cron = "0/5 * * * * ?")
* 时间间隔指定,例如:5秒
*/
@Scheduled(fixedDelay = 5000)
private void configureTasks(){
Boolean status = forestService.updateStatus();
System.out.println(status);
System.out.println("定时任务测试!!!");
}
}
Cron表达式参数分别表示:
秒(0~59) 例如0/5表示每5秒
分(0~59)
时(0~23)
日(0~31)的某天,需计算
月(0~11)
周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
@Scheduled:除了支持灵活的参数表达式cron之外,还支持简单的延时操作,例如 fixedDelay ,fixedRate 填写相应的毫秒数即可。
// Cron表达式范例:
每隔5秒执行一次:*/5 * * * * ?
每隔1分钟执行一次:0 */1 * * * ?
每天23点执行一次:0 0 23 * * ?
每天凌晨1点执行一次:0 0 1 * * ?
每月1号凌晨1点执行一次:0 0 1 1 * ?
每月最后一天23点执行一次:0 0 23 L * ?
每周星期天凌晨1点实行一次:0 0 1 ? * L
在26分、29分、33分执行一次:0 26,29,33 * * * ?
每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?
2.启动测试
启动应用,可以看到控制台打印出如下信息:
显然,使用@Scheduled 注解很方便,但缺点是当我们调整了执行周期的时候,需要重启应用才能生效,这多少有些不方便。为了达到实时生效的效果,可以使用接口来完成定时任务。
3.启动时就会在执行一次
有些时候,我们编写的程序就会挂掉。这时我们的定时任务会从新计时,但如果我们定时任务的周期是一个小时,而我们的系统在最后最后一分钟的时候挂了。
这个时候我们可以根据个人的需求给定时任务设置一个启动时就会在执行一次。
@PostConstruct 注解就可以
@PostConstruct是有java自己的注解,该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
所以这个注解只能在非静态的void方法上使用。
package com.hnbd.dome.timing;
import com.hnbd.dome.service.ForestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* 定时任务
*
* @创建人 江枫沐雪
* @创建时间 2021/6/11 15:48
*/
@Configuration //1.主要用于标记配置类
@EnableScheduling //2.开启定时任务
public class ForestTiming {
@Autowired
private ForestService forestService;
/**
* 指定时间执行任务 cron的时间格式 从零秒开始,每五秒执行一次
* @Scheduled(cron = "0/5 * * * * ?")
* 时间间隔指定,例如:5秒
*/
@Scheduled(fixedDelay = 5000)
@PostConstruct //启动时就会在执行一次
private void configureTasks(){
Boolean status = forestService.updateStatus();
System.out.println(status);
System.out.println("定时任务测试!!!");
}
}