/******************************************************************************* * Copyright 2014 Miami-Dade County * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.sharegov.cirm.stats; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; /** * A task, executing every full hour to load all stats and save them in store. * Not thread safe yet. Handle with care. * * @author Thomas Hilpold */ public class CirmClusterStatisticsTask { private static volatile CirmClusterStatisticsTask instance; private Timer timer; private TimerTask task; public static CirmClusterStatisticsTask getInstance(CirmClusterStatistics clusterStats, CirmClusterStatisticsStore store) { if (instance == null) { instance = new CirmClusterStatisticsTask(clusterStats, store); } return instance; } private CirmClusterStatisticsTask(final CirmClusterStatistics clusterStats, final CirmClusterStatisticsStore store) { task = new TimerTask() { @Override public void run() { clusterStats.updateAll(); try { store.writeAllFrom(clusterStats); System.out.println("Clusterstats auto update completed at " + new Date()); } catch(IOException e) { System.err.println("ERROR: Clusterstats auto update failed with: " + e + " at " + new Date()); e.printStackTrace(); } } }; } public void start() { if (timer == null) { timer = new Timer(); System.out.println("Clusterstats auto update scheduling for every full hour."); Date nextExecutionDate = getNextFullHour(); timer.scheduleAtFixedRate(task, nextExecutionDate, 60 * 60 * 1000); System.out.println("Timer started: First auto update scheduled for " + nextExecutionDate); } else { System.err.println("Timer already running"); } } public void stop() { timer.cancel(); timer = null; } Date getNextFullHour() { Calendar c = Calendar.getInstance(); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); c.add(Calendar.HOUR, 1); return c.getTime(); } }