@Scheduled Job的延伸应用
今天跟大家聊一个定时任务框架,@Scheduled 。目前需要实现的功能是在一天的固定时间段内每五分钟一次触发某个功能,每五分钟一次是好写的。但是一天的固定时间段内,我发现用cron表达式就很容易实现了,现在展示下代码上怎么实现:
private boolean workingTime() {
boolean workTime = false;
//timezone
ZoneId shanghai = ZoneId.of(ZoneCommon.SH_ZONE);
LocalDateTime shanghaiTime = LocalDateTime.now(shanghai);
int hour = shanghaiTime.getHour();
String syncTime = applicationProperties.getSyncTime();
//Default time
int start = 7;
int end = 18;
if (StringUtils.hasText(syncTime)) {
String[] values = syncTime.split("-");
if (values.length > 0) {
start = Integer.valueOf(values[0]);
}
if (values.length > 1) {
end = Integer.valueOf(values[1]);
}
}
if (hour >= start && hour <= end) {
workTime = true;
}
log.info("[workingTime]Get shanghai time {} and hour {} and workTime {} and syncTime {} ", shanghaiTime, hour, workTime, syncTime);
return workTime;
}
以上方法需要我们先在配置文件中写好一个时间段如9-23,那么他的意思就是在九点到23点执行。
配置如下:
@Data
@Component
public class ApplicationProperties {
@Value("${application.schedulingTimer.syncTime}")
private String syncTime;
}
//在配置文件中写入
schedulingTimer:
syncTime: 7-23
这个方法是用来判断当前时间是否满足目标时间段的方法,返回值为布尔类型,当我们需要给某个方法加上时间段判断时可以通过以下方式:
//@Scheduled(fixedDelayString = "${schedulingTimer.syncFixInterval}", initialDelayString = "${schedulingTimer.start.sycDeliveryNotice}")
public void sycDeliveryNotice() {
if (workingTime()) {
kingdeeService.sycDeliveryNotice();
}
}
比如当前我需要调用sycDeliveryNotice的方法,我就在外层加一个判断,满足则执行,不满足就不执行了。
还没有评论,来说两句吧...