Is it possible to run a “background” task during a Vaadin application without having an active client?
I have been trying to implement a background timer task to do email handling but it is only working while the client is active (from entering the URL in the browser). I am looking to make it work while the application is loaded without an active client from a browser.
Yes, but it has nothing to do with Vaadin. You can just create a Thread to run your background tasks. For this purpose, I’d suggest starting the Thread in a ServletContextListener.contextInitialized() method, and you can then stop it in the corresponding contextDestroyed() method.
See javax.servlet.ServletContextListener for details. Older servlet containers need a web.xml to define this, but with the latest (like in Tomcat 7) you can just annotate your class with @Weblistener.
Here’s the basic look:
@WebListener
public class ContextListener
implements ServletContextListener
{
private YourRunnableClass backgrounder;
public ContextListener()
{
}
public void finalize()
{
}
public void contextInitialized(ServletContextEvent sce)
{
backgrounder = new YourRunnableClass();
Thread thread = new Thread(backgrounder);
thread.setDaemon(true);
thread.setPriority(Thread.currentThread().getPriority()-1);
thread.start();
}
public void contextDestroyed(ServletContextEvent sce)
{
if ( backgrounder != null )
{
backgrounder.stop(); //generally sets a flag in your class that causes it to stop looping
synchronized(backgrounder)
{
backgrounder.notifyAll(); // notify it now so it can detect the stop flag set and end itself
backgrounder= null;
}
}
}
}