看了下大部分的JAVA Web的请求方式都是使用在Web.xml中配置监听器实现!
这里自己写了个Timer能同样达到一样的要求!而且可以自己控制 启动或关闭,而且可以设置1天内在6,9,12点执行该定时器,感觉
听灵活的!
啥样呢?
后台代码如下:
/** * @author qiyulin * @date 2016 05 06 * */ @Controller() @Scope("prototype") public class MapAction extends GenericAction{ private static final long serialVersionUID = -8570260939683969514L; private static MyTimer mt ; //定时器数据同步 private String msg; public String timer(){ String on = request().getParameter("on"); String times = request().getParameter("times"); if(empty(times)) times = "1"; if(!empty(on)&&"yes".equals(on)){ //启动定时器 mt =new MyTimer(times); mt.start(new MyTimerCallback(){ public void finshed(int status) { switch(status){ case 1: System.err.println("定时器:已触发"); break; case 0: System.err.println("定时器:未触发"); break; } } }); msg="定时器已被启动"; }else if(!empty(on)&&"no".equals(on)){ //关闭定时器 if(mt!=null){ mt.end(new MyTimerCallback(){ public void finshed(int status) { //do something System.out.println("定时器:已关闭"); } }); } msg="定时器已被关闭"; }else{ msg="Welcome to Timer"; } return AppConstants.RETURN_TYPE_FREEMARKER; } //空判断 private boolean empty(Object obj){ if(null!=obj&&!"".equals(obj)){ return false; } return true; } //内部类 class MyTimer{ private String hours; private Timer timer = new Timer(true); public MyTimer(String hours) { this.hours = hours; } public void start(final MyTimerCallback callback){ timer.schedule(new TimerTask(){ @SuppressWarnings("deprecation") @Override public void run() { Calendar cal = Calendar.getInstance(); String hs[] = hours.split(","); int hour= cal.getTime().getHours(); boolean b=Arrays.asList(hs).contains(String.valueOf(hour)); if(b){ callback.finshed(1); }else{ callback.finshed(0); } } }, 0,10*1000); } public void end(MyTimerCallback callback){ timer.cancel(); callback.finshed(2); } } //回调 interface MyTimerCallback{ void finshed(int status); } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
页面代码如下:
<html> <head> <meta charset="utf-8" /> <title>系统定时器管理工具</title> </head> <body> <h1 style="color: red">Welcome to Timer</h1> <h2>Open Timer</h2> <form action="Map_timer.action" method="post"> <input type="hidden" value="yes" name="on"/> <p>1天内执行定时器的小时点:<input type="text" name="times" value="1" /> 备注:1天内在6,9,12点执行该定时器,则填写: 3,6,9</p> <p><input type="submit" value="启动定时器"/></p> </form> <hr> <h2>Close Timer</h2> <form action="Map_timer.action" method="post"> <input type="hidden" value="no" name="on"/> <p><input type="submit" value="停止定时器"/></p> </form> </body> </html>
感觉挺好用的,哈哈,下班....
原创:http://blog.csdn.net/qilin001cs
时间: 2024-11-07 23:56:04