javaservletsscheduled-tasksservlet-filtershitcounter

Hit counter approach with Servlets


I want to create a hit counter register in my DB using Java Servlets. The main idea is use Filters and, in every user visit, increase the counter.

I don't want to make an update in the DB on every visit (I found this not too much efficient). I prefer to use an static variable that would be increased every visit and, at the end of the day, make an INSERT into the DB with the value of that variable and reset it to zero.

How could I do that? I don't know how to schedule an accion that say to my application every midnight make an INSERT and resets the variable...

Any idea?

Thank you! :)


Solution

  • After a long time searching for solutions, I found that Timer is not working well with Servlets, so I used this (and works great! :) This is the code for the filter:

    public class LogVisitorsListener implements ServletContextListener {
    
        private ScheduledExecutorService scheduler;
    
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            scheduler = Executors.newSingleThreadScheduledExecutor();
    
            // It will be executed every 1 hour
            scheduler.scheduleAtFixedRate(new DailyHitsRunnable(), 0, 1, TimeUnit.HOURS); 
        }
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            scheduler.shutdownNow();
        }
    }
    

    And my class DailyHitsRunnable:

    public class DailyHitsRunnable implements Runnable {
    @Override
        public void run() {
            try {
                // stuff here...
            } 
            catch(Throwable t) {
                // catch work here...
            }
        }
    }
    

    It's very important to use that try/catch to avoid stopping the runnable action stops when something fails.

    Regards!