美文网首页
java定时任务

java定时任务

作者: 木有鱼丸啦 | 来源:发表于2018-06-13 13:47 被阅读0次

    1.监听类继承ServletContextListener

    public class MyListen implements ServletContextListener {

    private UserMemberService userMemberService;//需要调用的对象

    Calendar calendar = Calendar.getInstance(); 

    private Timer timer = null;

    @Override

    public void contextInitialized(ServletContextEvent sce) {

    //获取对象,此处对象不能直接bean注入获得,因为spring容器不支持多线程的注入

    userMemberService = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(UserMemberService.class);

    //设置每天定时执行时间

    calendar.set(Calendar.HOUR_OF_DAY, 24); 

    calendar.set(Calendar.MINUTE,0); 

    calendar.set(Calendar.SECOND, 0); 

    Date time = calendar.getTime();

    timer = new Timer(true);

    timer.schedule(new MyTask(userMemberService), time);

    }

    @Override

    public void contextDestroyed(ServletContextEvent sce) {

    timer.cancel();

    }

    }

    2.

    public class MyTask extends TimerTask {

    private UserMemberService userMemberService;

    public MyTask(UserMemberService userMemberService) {

        this.userMemberService = userMemberService;

      }

    @Override

    public void run() {

    System.out.println(userMemberService==null);//判断对象是否实例化

    userMemberService.updateMember();//调用自己的对象方法

    }

    }

    3.web.xml配置监听器

    <listener>

    <listener-class>

    com.huihe.gt.controller.user.member.MyListen

    </listener-class>

    </listener>

    相关文章

      网友评论

          本文标题:java定时任务

          本文链接:https://www.haomeiwen.com/subject/spsjeftx.html