1 |
package dk.thoerup.traininfoservice; |
2 |
|
3 |
import java.util.Timer; |
4 |
import java.util.TimerTask; |
5 |
|
6 |
import javax.servlet.ServletContext; |
7 |
import javax.servlet.ServletContextEvent; |
8 |
import javax.servlet.ServletContextListener; |
9 |
|
10 |
|
11 |
public class StatisticsListener implements ServletContextListener { |
12 |
|
13 |
Timer timer = null; |
14 |
int update_interval; |
15 |
|
16 |
public void contextInitialized(ServletContextEvent sce) { |
17 |
|
18 |
update_interval = getUpdateInterval( sce.getServletContext() ); |
19 |
if ( update_interval > 0 ) { |
20 |
timer = new Timer(); |
21 |
|
22 |
TimerTask statsUpdate = new TimerTask() { |
23 |
@Override |
24 |
public void run() { |
25 |
Statistics.getInstance().saveStats(); |
26 |
} |
27 |
}; |
28 |
|
29 |
timer.schedule(statsUpdate, 0, update_interval); |
30 |
} |
31 |
} |
32 |
|
33 |
|
34 |
public void contextDestroyed(ServletContextEvent sce) { |
35 |
if ( update_interval > 0 ) { |
36 |
timer.cancel(); |
37 |
Statistics.getInstance().saveStats(); |
38 |
} |
39 |
} |
40 |
|
41 |
private int getUpdateInterval(ServletContext cntx) { |
42 |
int interval = 0; |
43 |
try { |
44 |
String intervalStr = cntx.getInitParameter("stats_interval"); |
45 |
interval = Integer.parseInt(intervalStr); |
46 |
} catch (Exception e) {} |
47 |
|
48 |
return interval; |
49 |
} |
50 |
} |