关于springboot如何做一个定时任务
- 首先我们需要用到Tomcat的监听器ServletContextListener,我们将需要写的一个定时任务类继承ServletContextListener,ServletContextListener有两个重写方法,分别是contextInitialized和contextDestroyed,将你需要服务器开始时要监控的定时任务写在contextInitialized方法中,将你需要在服务器关闭时做的一些处理写在contextDestroyed,就可以很方便的完成你的需求,代码如下:
@WebListener
public class ContextListener implements ServletContextListener {
@Autowired
private CustomerService customerServiceImpl;
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
// 定时任务
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Calendar cal = Calendar.getInstance();
int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
if (day_of_month == 20) {
customerServiceImpl.userBonus();
}
}
}, 0, 3600 * 24 * 1000);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("Destroyed");
}
}
2.@WebListener注解是springboot监听器的一个注解,所有监听器实体类都需要加上这个注解,并且在springboot的启动类Application当中,还需要加上一个能扫描全局的监听器过滤器的一个注解,那就是@ServletComponentScan,代码如下:
@ServletComponentScan
@SpringBootApplication
@MapperScan("*.mapper")
public class MMApplication {
public static void main(String[] args) {
SpringMMApplication.run(MMApplication.class, args);
}
}