I'm scheduling background task to run in fixed-intervals, but as tomcat is running in multiple instances (i.e. multiple start Apache servers; 3 in my case), then the task runs 3 times in each interval.. I would like it to run once (no matter the number of Tomcat instances running).
I'm running a servlet loaded on startup (in web.xml) which will initiate my task:
<servlet>
<servlet-name>OnInit</servlet-name>
<servlet-class>box.OnInit</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
OnInit class initiate single instance of that class:
public class BGTaskRefresh {
private static BGTaskRefresh refreshTaskFactory = null;
private final Timer timer = new Timer();
public BGTaskRefresh() {}
public static void init()
{
if( refreshTaskFactory == null )
{
refreshTaskFactory = new BGTaskRefresh();
refreshTaskFactory.start();
}
}
public void start()
{
timer.schedule(
new TimerTask()
{
public void run()
{
boxService box = new boxService();
box.refreshMethod();
}
},
5 * 60 * 1000, // 5-Min Delay for first run
60 * 60 * 1000); // 60-Mins (Interval between 2 runs)
}
}