2

I have a MySQL database running on my localhost. To this database I have JDBC-connection. Over a RESTful WebService a softwareagent puts results into this database. I implemented a garbage collector in Java and want to execute that garbage collector after a certain period. My aim is that I do not have too many entries in the table.

The Garbage Collector looks as follows:

public void collectGarbageResults() {
    ArrayList<Integer> ids = new ArrayList<Integer>();
    ResultSet rs = this.execQuery("SELECT * FROM results");
    try {
        while (rs.next()) {
            if ( (System.currentTimeMillis()) - (Timestamp.valueOf(rs.getString("tmstmp")).getTime()) > Long.parseLong(appconfigs.get("resultstableactuality")) ) {
                ids.add(rs.getInt("id"));
            }
        }

        for (Integer i : ids) {
            this.deleteResultsWhereId(i);
        }           
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

The method I call looks as follows:

private void deleteResultsWhereId(int id) {
    retint = this.updateQuery("DELETE FROM results WHERE id=" + id + ";");
}

I am using JSF in an Eclipse's Dynamic Web Project and these methods are implemented in a managed bean. I am going to store the interval in an XML-file which I use for my application's configuration. Over the variable appconfigs I call the method 'get' and ask for the node containing my interval.

Now my question:

How can I call the method of the garbage collector after a certain period in my WebApp?

If you have any questions do not hesitate to comment.

My Solution :

@WebListener
public class BackgroundJobManager implements ServletContextListener{

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        long delayToStart   = 0;
        long numberOfUnits  = 60;
        TimeUnit tu = TimeUnit.SECONDS;
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new ExecuteGarbageCollector(), delayToStart, numberOfUnits, tu);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}

The class I call implements Runnable as follows:

public class ExecuteGarbageCollector implements Runnable{

    @Override
    public void run() {
        DAO dao = new DAO();
        dao.collectGarbageResults();
    }

}
silenum
  • 149
  • 1
  • 2
  • 11

3 Answers3

2

You could use ScheduledExecutorService or Quartz

Quartz has a lot of facilities, but If you choose ScheduledExecutorService you don't have to add any new dependencies to your project. and as you just want this scheduled task, it's simple.

 ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
  scheduler.scheduleAtFixedRate(...);

Take a look at some comments about both in: Quartz vs. ScheduledExecutorService in Java web application

Community
  • 1
  • 1
Inanda Menezes
  • 1,796
  • 13
  • 17
  • 1
    I accepted your answer because both options work. I don't know yet how to include them into my existing application, but I am sure this will be soon, owing to your last link. Thank you! – silenum Jan 22 '15 at 10:07
1
  1. Check out a scheduler library. You can use Quartz for example.
  2. Call Java from MySQL. You could either have this kicked off by a job or trigger
  3. Just stick to SQL and ignore running this in Java. Probably the easiest if you are good at SQL. Then you can encapsulate this in a SPROC or trigger.

It's your choice whether this should live in your web-app or in your database. I've used both methods for executing timed SQL calls and tend to prefer the code oriented approach

Community
  • 1
  • 1
stevebot
  • 23,275
  • 29
  • 119
  • 181
  • Unfortunately I am not this good at SQL. But I am going to use Quartz or the ScheduledExecutorService. Thank you for your effort. – silenum Jan 22 '15 at 10:02
1

The actual question could have well been how to call a function after a specific interval of time? Take a look at : How to call a method after some specific interval of time in Java and java: run a function after a specific number of seconds

Community
  • 1
  • 1
DoubleDotM
  • 61
  • 4