java 服务器 定时器_Java定时器

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();

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值