Java中,后台要执行一个重复的动作,单独的线程操作
1,手动启用
新建定时器
schedule方法的参数
第一个,定时器对象
第二个,定时器循环周期
Timer timer = new Timer(true); timer.schedule(new MyTask(), period);
定时器的实现类
public class MyTask extends TimerTask{ @Override public void run() { system.out.println("启动定时器"); } }
--------------------------------------------------------------------------------
2,自动启动(web工程中常用)
实例中,实现服务器启动,启动一天后运行定时器,之后每过一天执行一次,timer.schedule方法实现操作
schedule方法的参数
第一个,定时器对象
第二个,什么时候启动定时器
第三个,定时器循环周期
public class ContextListener implements ServletContextListener { private Timer timer; public Timer getTimer() { return timer; } public void setTimer(Timer timer) { this.timer = timer; } @Override public void contextInitialized(ServletContextEvent arg0) { timer = new Timer(true); CleanLogTask cleanLogTask = new CleanLogTask(); ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(arg0.getServletContext()); cleanLogTask.setApplicationContext(applicationContext); timer.schedule(cleanLogTask, 24*3600*1000, 24*3600*1000); } @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub }
定时器实现类
public class CleanLogTask extends TimerTask{ public CleanLogTask() { super(); } public CleanLogTask(ApplicationContext applicationContext) { super(); this.applicationContext = applicationContext; } private ApplicationContext applicationContext; public ApplicationContext getApplicationContext() { return applicationContext; } public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public void run() { LoginService loginService = (LoginService) applicationContext.getBean("loginService"); loginService.deleteMonthBeforeAccessLog(); } }