title: Stop @Schedule EJB gracefully when shutting down application server
body: <p>I have a stateless EJB with a method that should executed periodically. This works well so far. However, I want the stop the method gracefully when it is running while shutting down application server. Therefore, I have implemented a <code>stop()</code> method annotated with <code>@PreDestroy</code>.</p>
  <p>However, the <code>stop()</code> method does not work as expected. When stopping my application server while <code>schedule()</code> is running, the application server waits until <code>schedule()</code> terminates and calls <code>stop()</code> only afterwards.</p>
  <pre class="lang-java prettyprint-override"><code>@Stateless
  public class TestService {
  
      private static final Logger logger = Logger.getLogger(TestService.class);
  
      private volatile boolean shutdown = false;
  
      @Schedule(hour = &quot;*&quot;, minute = &quot;*&quot;, second = &quot;*/15&quot;, persistent = false)
      public void schedule() throws InterruptedException {
          logger.info(&quot;Start execution&quot;);
          for (int i = 0; !shutdown &amp;&amp; i &lt; 10; ++i) {
              logger.info(&quot;Step &quot; + i);
              Thread.sleep(1000);
          }
          logger.info(&quot;Stopped execution&quot;);
      }
  
      @PreDestroy
      public void stop() {
          logger.info(&quot;Trigger stop&quot;);
          shutdown = false;
      }
  
  }
  </code></pre>
  <p>Here, I have posted only a minimal example EJB for reproducing my issue. In my real EJB, it is even worse. When executing any transaction after triggering the server shutdown, the application server (JBoss EAP 7.1 with WildFly 11) throws a <code>ComponentIsStoppedException</code>. So, I have no chance to gracefully shutdown my EJB.</p>