A database cleanup task should indeed be run on the server side periodically. In Java projects where I have participated, we have done similar tasks with Tomcat or Jetty using ServletContextListener. Other servers, e.g. node, have their own mechanisms of course.
You create a class implementing this interface, whose methods get called when your servlet is started or destroyed.
In the startup method you create a thread that cleans the db up in a loop every hour, until the servlet is destroyed:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class DBCleanupContextListener implements ServletContextListener
{
private ExecutorService threadPool;
private DBCleanupTask dbCleanupTask;
public DBCleanupContextListener()
{
threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
dbCleanupTask = new DBCleanupTask();
}
@Override
public void contextInitialized(ServletContextEvent arg0)
{
threadPool.execute(dbCleanupTask);
// submit additional tasks here if needed...
}
@Override
public void contextDestroyed(ServletContextEvent arg0)
{
dbCleanupTask.shutdown();
threadPool.shutdown();
}
class DBCleanupTask implements Runnable
{
boolean finished = false;
@Override
public void run()
{
while (!finished)
{
System.out.println("db cleanup code goes here ....");
try
{
Thread.sleep(60 * 60 * 1000); // sleeps 1 hour = 60min*60sec*1000ms
}
catch (InterruptedException e)
{
finished = true;
}
}
}
public void shutdown()
{
finished = true;
}
}
}
I have run this code with Tomcat, Jetty and Spring Boot. Theoretically it should run on any JavaEE server, but you need to research how to configure the servlet. On Tomcat for example it needs to be added to the web.xml, as described here:
<web-app ...>
<listener>
<listener-class>
com.example.DBCleanupContextListener
</listener-class>
</listener>
</web-app>