有时候,我们需要在Java中定义一个定时器来轮询操作,比如每隔一段时间查询、删除数据库中的某些数据等,下面记录一下一种简单实现方式
1,首先新建一个类,类中编写方法来实现业务操作
public class MailQuartz { @Autowired private MailServiceImpl sendMail; @Autowired private TimerServiceImpl timerServiceImpl; public void Quartz(){ String timer = getTimerStatus(); if(!timer.equals("1")){ System.out.println("定时器未开启"); return; } List<T> result = new ArrayList<T>(); //查询出需要发送邮件的对象 result = timerServiceImpl.checkSendMail(); public void deleteOldEInvoices(){ timerServiceImpl.deleteOldEInvoices(); } //读取配置文件中的值,开启或者关闭定时器 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"); } }