Spring实现定时器
定时删除数据库表中数据
功能点:Spring的task-scheduled
1、实现业务功能
/** * 功能描述: 定时清理30天前内交易表的数据(时间:00:15) */@Componentpublic class TraceShortTimeClearTask { static Logger logger = LoggerFactory.getLogger(TraceShortTimeClearTask.class); @Autowired private TraceChannelMessageShortTimeService traceChannelMessageShortTimeService; /** * @description:定时清理30天前短时间内交易表的数据 */ public void traceShortTimeClear() { Date newDate = new Date(); LocalDate deleteDate = getDate(newDate,30); try{ int i = traceChannelMessageShortTimeService.deleteTrace(deleteDate); if (i >= 1){ logger.info("TraceShortTimeClearTask------------->traceShortTimeClear清理30天前短时间内交易表的数据成功"); } }catch (Exception e){ logger.error("删除30天前的数据失败!" e.getMessage()); } } /** * 获取时间 */ public static LocalDate getDate(Date now,int days){ Calendar calendar = Calendar.getInstance(); calendar.setTime(now); calendar.add(Calendar.DATE, -days); Date deleteDate = calendar.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String dateString = sdf.format(deleteDate); DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate localDate = LocalDate.parse(dateString,fmt); return localDate; }}
2、配置定时规则
2.1 引入命名空间
<beans xmlns:task="http://www.springframework.org/schema/task"></beans>
2.2 导入xsi文件
<beans xsi:schemaLocation=" http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"></beans>
2.3 配置实现类
<bean id="clearTask" class="com.red.task.TraceShortTimeClearTask"></bean>
2.4 配置定时规则
<task:scheduled-tasks> <!-- ref = "bean的id" method = "实现类的方法名" cron = "定时规则,秒,分,时,天,月,周,年" --> <task:scheduled ref="clearTask" method="traceShortTimeClear" cron="0 15 0 * * ?"/></task:scheduled-tasks>
3、数据库语句
<!--定时清理30天前短时间内交易表的数据--><delete id="deleteTrace"> delete from 表名 where 字段名 <#{deleteDate}'%'</delete>
赞 (0)