tomcat启动时自动执行代码

1、实现监听启动的接口

package cn.geekapp.timer;

import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyListener implements ServletContextListener{
	
	/**
	 * 定时器
	 */
	private static Timer mTimer = null;
	/**
	 * 定时器启动间隔
	 */
	private static final long mPeriod = 1 * 10 * 1000L;//10秒

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		// TODO Auto-generated method stub
		System.out.println("contextDestroyed begin");
		if(mTimer != null){
			mTimer.cancel();
		}
		System.out.println("contextDestroyed end");
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		// TODO Auto-generated method stub
		System.out.println("contextInitialized begin");
		mTimer = new Timer(true);
		mTimer.scheduleAtFixedRate(new MyTimerTask(), mPeriod, mPeriod);
		System.out.println("contextInitialized end");
	}

}

2、定义TimerTask

package cn.geekapp.timer;

import java.util.TimerTask;

public class MyTimerTask extends TimerTask{
	
	private static boolean isRun = false; 

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			if(isRun){
				System.out.println("task is running,return!");
				return;
			}
			isRun = true;
			System.out.println("MyTimerTask run at time "+System.currentTimeMillis());
			//业务逻辑代码
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			isRun = false;
		}
	}

}

3、web.xml添加监听

  
	cn.geekapp.timer.MyListener
  

原创内容转载请保留出处GEEK笔记(https://www.geekapp.cn/)。

原创博客,转载请标明出处:https://www.geekapp.cn/archives/282.html
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇