需求:当通知住院时间超时,患者还没有来医院,则自动判为拒绝入院,我这里是将字段notice_delete_status值‘0’改为‘1’。
重点是自动判为,可以知道是使用注解@EnableScheduling定时任务,下面来探讨一下。
首先需知道什么是定时任务。
定时任务——即什么时间做什么事。
具体操作:
- pom.xml中导入必要的依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<dependencies>
<!-- SpringBoot 核心组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 需在Application启动类上加注解@EnableScheduling启动定时任务
@SpringBootApplication
@EnableScheduling //启用定时任务
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3.在JpaRepository层下添加一个用来查询超时的数据并返回一个列表的方法
@Repository
public interface HospitalizationNoticeMapper extends JpaRepository<HospitalizationNotice,Long> {
/**
* 查询超时通知时间
* @param currentDate
* @return
*/
@Transactional
@Query("SELECT n FROM hospitalization_notice n WHERE n.noticeHospitalizationTime < ?1 AND n.noticeDeleteStatus = '0'")
List<HospitalizationNotice> findTimeoutNotices(@Param("currentDate") Date currentDate);
}
查询状态为0(即未删除)并且超时的数据列表
- 在需要的类下面设置定时任务
/**
* 自动判断超时
*/
@Scheduled(fixedDelay = 60000) // 定时间隔为1分钟(可以根据需要调整)
public void checkAndHandleTimeoutNotice() {
List<HospitalizationNotice> timeoutNotices = mapper.findTimeoutNotices(new Date());
for (HospitalizationNotice notice : timeoutNotices) {
notice.setNoticeDeleteStatus("1");
mapper.save(notice);
}
}
遍历列表,将状态改为1——删除,mapper.save()保存。