0

I have a Java Servlet running in Tomcat8 (within eclipse). When the Servlet is called I would like to execute a command and call a method, that uses a Scheduler.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Scheduler s = new Scheduler();
        s.doStuff();

.

 package xy;
 import javax.ejb.Schedule;
 import javax.ejb.Singleton;

  @Singleton
  public class Scheduler {

    private int counter = 0;

    @Schedule(second = "*/5", minute = "*", hour = "*", info="Every 5 seconds")
    public void  doStuff(){
        counter++;
        System.out.println("counter: " +counter);           
    }
}

Following my logic, every 5 seconds I should see a counter println getting higher and higher. But nothing happens.

DavidS
  • 4,384
  • 2
  • 23
  • 51
Gero
  • 10,601
  • 18
  • 58
  • 101

3 Answers3

3

Tomcat is not a complete Java EE container. It implements only the Java Servlet and JavaServer Pages technologies, so you will not be able to use EJBs (@Singleton) or the Timer Service (@Schedule). Consider using a Java EE server or ScheduledExecutorService.

See also

DavidS
  • 4,384
  • 2
  • 23
  • 51
2

Tomcat is not EJB container

The most simple way to do scheduled execution in tomcat - use java.util.concurrent.ScheduledExecutorService.

@WebListener
public class MyAppContextListener implements ServletContextListener {
    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        //init sheduler
        scheduler = Executors.newSingleThreadScheduledExecutor();
        //!!!Shedule task
        scheduler.scheduleAtFixedRate(...);
    }

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

To shedule task uses:

scheduler.scheduleAtFixedRate(command, initialDelay, period, unit);

command - Instance of class which implements java.lang.Runnable

initialDelay - delay before first run in time units

period - time in units between task executions

unit - java.util.concurrent.TimeUnit (ex. TimeUnit.MINUTES)

cache
  • 672
  • 2
  • 14
  • 26
1

Try jboss open src free version OR http://tomee.apache.org/ Tommy, it has tomcat underneath. Like others have said tomcat is not a full app container.

tgkprog
  • 4,405
  • 4
  • 39
  • 66