java timer 重启服务器_服务器启动完成执行定时任务Timer,TimerTask

由于项目需求:每隔一段时间就要调外部接口去进行某些操作,于是在网上找了一些资料,用了半天时间弄好了,代码:

1 importjava.util.TimerTask;2

3 public class AccountTask extendsTimerTask {4

5 @Override6 public voidrun() {7 System.out.prinln("开始执行定时任务业务");8 }9 }

1 importjava.util.Timer;2

3 importjavax.servlet.ServletContextEvent;4 importjavax.servlet.ServletContextListener;5

6 public class AccountTimerListener implementsServletContextListener {7

8 private Timer timer = null;9

10 @Override11 public voidcontextInitialized(ServletContextEvent event) {12 timer = new Timer(true);13 event.getServletContext().log("定时器已启动");14 //服务器启动后,延迟7秒启动,5秒执行一次

15 timer.scheduleAtFixedRate(new AccountTask(), 7 * 1000, 5 * 1000);

16 }17

18 @Override19 public voidcontextDestroyed(ServletContextEvent event) {20 if (timer != null) {21 timer.cancel();22 event.getServletContext().log("定时器销毁");23 }24 }25 }

然后在web.xml文件中配置监听

1

2 com.xxx.AccountTimerListener

3

启动之后,会发现没隔5秒打印一次: 开始执行定时任务业务 。

然而,当调度类中调用service层业务时,启动tomcat后,执行定时任务时会报空指针异常,这是由于这个定时任务目前只是一个普通的类,我们需要将这个定时任务注入到spring中,监听。

解决方案如下:

1 packagecom.test.utils;2

3 importjavax.servlet.ServletContextEvent;4 importjavax.servlet.ServletContextListener;5

6 importorg.springframework.context.ApplicationContext;7 importorg.springframework.web.context.WebApplicationContext;8 importorg.springframework.web.context.support.WebApplicationContextUtils;9

10 public class SpringInit implementsServletContextListener {11

12 private staticWebApplicationContext springContext;13

14 publicSpringInit() {15 super();16 }17

18 @Override19 public voidcontextDestroyed(ServletContextEvent event) {20 //TODO Auto-generated method stub

21 }22

23 @Override24 public voidcontextInitialized(ServletContextEvent event) {25 springContext =WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());26 }27

28 public staticApplicationContext getApplicationContext() {29 returnspringContext;30

31 }32

33 }

web.xml文件:

1

2

3

4

5

6 com.test.utils.SpringInit

7

若  context:component-scan  出报错,可能是因为没有引入标签。

在xmlns:xsi 里加上

1 http://www.springmodules.org/schema/cache/springmodules-cache.xsd http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd

xsi:schemaLocation里加上

1 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

上面的问题解决。

最后,我们掉用service之前,这样来获取bean:

DetailService detailService = (DetailService) SpringInit.getApplicationContext().getBean("detailService");

然后就可以掉用service层业务进行定时任务了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值