Java 定时器示例_Java 定时器小示例
大家好,又见面了,我是你们的朋友全栈君。
有时候,我们需要在Java中定义一个定时器来轮询操作,比如每隔一段时间查询、删除数据库中的某些数据等,下面记录一下一种简单实现方式
1,首先新建一个类,类中编写方法来实现业务操作
public classMailQuartz {
@AutowiredprivateMailServiceImpl sendMail;
@AutowiredprivateTimerServiceImpl timerServiceImpl;public voidQuartz(){
String timer=getTimerStatus();if(!timer.equals(“1”)){
System.out.println(“定时器未开启”);return;
}
List result = new ArrayList();//查询出需要发送邮件的对象
result =timerServiceImpl.checkSendMail();public voiddeleteOldEInvoices(){
timerServiceImpl.deleteOldEInvoices();
}//读取配置文件中的值,开启或者关闭定时器
publicString getTimerStatus(){
InputStream inputStream= this.getClass().getClassLoader().getResourceAsStream(“application.properties”);
Properties pro= newProperties();try{
pro.load(inputStream);
}catch(IOException e) {
e.printStackTrace();
}return pro.getProperty(“timer”);
}
}
View Code
这里我们创建了一个类MailQuartz,然后在类中定义了两个方法Quartz和deleteOldEInvoices,并且在这两个方法中,我们实现了调用service处理相应的业务,ok,下面让我们配置其触发方式。
2,类中的方法触发配置信息,我们写在applicationContext.xml文件中
class=”org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean”>
Quartz
class=”org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean”>
deleteOldEInvoices
0 0/5 * * * ? *
0 0 0 1 * ? *
class=”org.springframework.scheduling.quartz.SchedulerFactoryBean”>
View Code
查看代码,我们可以发现,需要配置我们类MailQuartz、方法Quartz和deleteOldEInvoices的相关信息,然后触发时间的间隔,我们用corn表达式去约束,这样,我们就可以为实现多个方法实现定时器。
3,最后呢,为了优化,由于定时器的触发效果是,项目一启动,定时器就会触发,但是在测试阶段或者你不想让定时器触发,因为他会更改你数据库中的测试数据,那么我们就可以在方法之前读取配置文件中的某个变量值,然后做判断,
String timer = getTimerStatus(); //调用getTimerStatus()方法,取得配置文件中定义的控制值
if(!timer.equals(“1”)){//然后根据值来阻止定时器的运行
System.out.println(“定时器未开启”);
return;
}
//读取配置文件中的值,开启或者关闭定时器
public String getTimerStatus(){
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(“application.properties”);
Properties pro = new Properties();
try {
pro.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return pro.getProperty(“timer”); //这里的timer值就是在application.properties中定义的
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。