简体   繁体   中英

How to start @Schedule method in Java EJB in Tomcat

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.

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

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 )

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM