工作中很多地方都需要使用定时器这个方法,比如定时操作数据库,定时更新等等。
java中有定时器的方法,比较麻烦,springboot中直接用注解就能实现。下面看如何实现
//一定要加上Service注解,否则无法找到这个方法
@Service
public class mapperTest {
@Autowired
private testMapper mapper;
@Scheduled(cron = "0/5 * * * * *")
public void mes(){
System.out.println("你好");
}
//在你需要调用的方法上面加上这个注解,现在意思是20秒执行一次
@Scheduled(cron = "0/20 * * * * *")
public void state() throws Exception{
//调用mapper中的方法
List<String> mes = mapper.getMes();
for (int i = 0; i <mes.size() ; i++) {
System.out.println(mes.get(i));
}
}
下面看一下mapper中的方法
@Mapper
public interface testMapper {
public List<String> getMes();
}
也很简单,注意加上mapper这个注解。mapper调用xml中的sql。再看一下xml中sql怎么写。
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.module.dao.testMapper">
<select id="getMes" resultType="String">
select * from test
</select>
</mapper>
namespace就是你的mapper全类名,id就是mapper中的方法resultType是输出参数类型。
在配置文件中配置你的参数
也就是application.properties
spring.datasource.url=jdbc:mysql:/***。***.***.**:3306/test?useSSL=false&characterEncoding=utf8&allowMultiQueries=true&useUnicode=true
spring.datasource.username=root
#
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
最后在启动类上加上开启注解的方法。
@EnableScheduling
@SpringBootApplication
//@MapperScan("com.example.demo.module.dao.testMapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
mapperscan是扫描你的mapper包的,可以加,也可以不加,结果都是一样的,他会自动去查找你的mapper。
好了,可以去测试了,可以看到控制台打印出了查询数据库的结果。