2017-10-14 144 views

回答

1

這是我終於想出了WildFly 11(的Java EE 7)不使用任何配置更改/補充的beans.xml/web.xml文件:

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

import java.util.concurrent.CountDownLatch; 
import java.util.concurrent.TimeUnit; 

import javax.annotation.PostConstruct; 
import javax.annotation.PreDestroy; 
import javax.annotation.Resource; 
import javax.ejb.Singleton; 
import javax.ejb.Startup; 
import javax.enterprise.concurrent.ManagedThreadFactory; 

@Startup 
@Singleton 
public class IndexingTask implements Runnable { 

    private static final Logger LOG = LoggerFactory.getLogger(IndexingTask.class); 

    private Thread taskThread = null; 
    private final CountDownLatch shutdownLatch = new CountDownLatch(1); 

    @Resource 
    private ManagedThreadFactory threadFactory; 

    @PostConstruct 
    public void postConstruct() { 
     taskThread = threadFactory.newThread(this); 
     taskThread.start(); 
    } 

    @PreDestroy 
    public void preDestroy(){ 
     shutdownLatch.countDown(); 
     try { 
      taskThread.join(); 
     } catch (InterruptedException ex) { 
      LOG.warn("interrupted while waiting for " + taskThread + " to shut down", ex); 
     } 
    } 

    @Override 
    public void run() { 
     LOG.info("started"); 
     try { 
      while (!shutdownLatch.await(100, TimeUnit.MILLISECONDS)) { 
      } 
     } catch (InterruptedException ex) { 
      LOG.warn("", ex); 
     } 
     LOG.info("stopped"); 
    } 
} 

https://gruust.stream/2017/10/15/how-to-run-manage-a-container-background-thread-in-java-ee-7-

參見Java EE 7 containers: initialize bean at startup without adding it to beans.xml?