| :index-group: EJB |
| :jbake-type: page |
| :jbake-status: status=published |
| = Schedule Expression (Cronograma Expressão) |
| |
| Neste exemplo, exercitamos o `TimerService`. |
| ____ |
| ``A interface TimerService fornece componentes de bean corporativo com |
| acesso ao serviço de cronômetro fornecido pelo contêiner. O EJB Timer Service permite que os beans de entidade, os beans de sessão sem estado e os beans controlados por mensagem sejam registrados para eventos de retorno de chamada do cronômetro em um tempo especificado, após um tempo decorrido especificado ou após um intervalo especificado.'' |
| ____ |
| |
| Para uma descrição completa do TimerService, consulte o tutorial Java EE dedicado ao |
| http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html[Timer Service]. |
| |
| == FarmerBrown |
| |
| No `PostConstruct`, criamos 5 temporizadores programáticos. Provavelmente, os quatro primeiros não serão acionados durante a execução do teste; no entanto, o último terá o tempo limite esgotado algumas vezes. |
| |
| Cada cronômetro contém um atributo de informação, que pode ser inspecionado no tempo limite. |
| |
| [source,java] |
| ---- |
| package org.superbiz.corn; |
| |
| import jakarta.annotation.PostConstruct; |
| import jakarta.annotation.Resource; |
| import jakarta.ejb.Lock; |
| import jakarta.ejb.LockType; |
| import jakarta.ejb.ScheduleExpression; |
| import jakarta.ejb.Singleton; |
| import jakarta.ejb.Startup; |
| import jakarta.ejb.Timeout; |
| import jakarta.ejb.Timer; |
| import jakarta.ejb.TimerConfig; |
| import jakarta.ejb.TimerService; |
| import java.util.concurrent.atomic.AtomicInteger; |
| |
| /** |
| * É aqui que programamos todos os trabalhos de milho do fazendeiro Brown(FarmerBrown) |
| * |
| * @version $Revision$ $Date$ |
| */ |
| @Singleton |
| @Lock(LockType.READ) // permite que os temporizadores sejam executados em paralelo |
| @Startup |
| public class FarmerBrown { |
| |
| private final AtomicInteger checks = new AtomicInteger(); |
| |
| @Resource |
| private TimerService timerService; |
| |
| @PostConstruct |
| private void construct() { |
| final TimerConfig plantTheCorn = new TimerConfig("plantTheCorn", false); |
| timerService.createCalendarTimer(new ScheduleExpression().month(5).dayOfMonth("20-Last").minute(0).hour(8), plantTheCorn); |
| timerService.createCalendarTimer(new ScheduleExpression().month(6).dayOfMonth("1-10").minute(0).hour(8), plantTheCorn); |
| |
| final TimerConfig harvestTheCorn = new TimerConfig("harvestTheCorn", false); |
| timerService.createCalendarTimer(new ScheduleExpression().month(9).dayOfMonth("20-Last").minute(0).hour(8), harvestTheCorn); |
| timerService.createCalendarTimer(new ScheduleExpression().month(10).dayOfMonth("1-10").minute(0).hour(8), harvestTheCorn); |
| |
| final TimerConfig checkOnTheDaughters = new TimerConfig("checkOnTheDaughters", false); |
| timerService.createCalendarTimer(new ScheduleExpression().second("*").minute("*").hour("*"), checkOnTheDaughters); |
| } |
| |
| @Timeout |
| public void timeout(Timer timer) { |
| if ("plantTheCorn".equals(timer.getInfo())) { |
| plantTheCorn(); |
| } else if ("harvestTheCorn".equals(timer.getInfo())) { |
| harvestTheCorn(); |
| } else if ("checkOnTheDaughters".equals(timer.getInfo())) { |
| checkOnTheDaughters(); |
| } |
| } |
| |
| private void plantTheCorn() { |
| // Escave o plantador !!! |
| } |
| |
| private void harvestTheCorn() { |
| // Desenterre a colheitadeira !!! |
| } |
| |
| private void checkOnTheDaughters() { |
| checks.incrementAndGet(); |
| } |
| |
| public int getChecks() { |
| return checks.get(); |
| } |
| } |
| ---- |
| |
| == FarmerBrownTest |
| |
| A classe de teste adquire uma instância do contexto e espera por 5 |
| segundos para dar aos temporizadores uma chance de expirar. |
| |
| [source,java] |
| ---- |
| package org.superbiz.corn; |
| |
| import junit.framework.TestCase; |
| |
| import jakarta.ejb.embeddable.EJBContainer; |
| import javax.naming.Context; |
| |
| import static java.util.concurrent.TimeUnit.SECONDS; |
| |
| /** |
| * @version $Revision$ $Date$ |
| */ |
| public class FarmerBrownTest extends TestCase { |
| |
| public void test() throws Exception { |
| |
| final Context context = EJBContainer.createEJBContainer().getContext(); |
| |
| final FarmerBrown farmerBrown = (FarmerBrown) context.lookup("java:global/schedule-expression/FarmerBrown"); |
| |
| // Dê ao fazendeiro brown uma chance de fazer algum trabalho |
| Thread.sleep(SECONDS.toMillis(5)); |
| |
| final int checks = farmerBrown.getChecks(); |
| assertTrue(checks + "", checks > 4); |
| } |
| } |
| ---- |
| |
| == Executando |
| |
| [source,console] |
| ---- |
| ------------------------------------------------------- |
| T E S T S |
| ------------------------------------------------------- |
| Running org.superbiz.corn.FarmerBrownTest |
| Apache OpenEJB 4.0.0-beta-1 build: 20111002-04:06 |
| http://tomee.apache.org/ |
| INFO - openejb.home = /Users/dblevins/examples/schedule-expression |
| INFO - openejb.base = /Users/dblevins/examples/schedule-expression |
| INFO - Using 'jakarta.ejb.embeddable.EJBContainer=true' |
| INFO - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service) |
| INFO - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager) |
| INFO - Found EjbModule in classpath: /Users/dblevins/examples/schedule-expression/target/classes |
| INFO - Beginning load: /Users/dblevins/examples/schedule-expression/target/classes |
| INFO - Configuring enterprise application: /Users/dblevins/examples/schedule-expression |
| WARN - Method 'lookup' is not available for 'jakarta.annotation.Resource'. Probably using an older Runtime. |
| INFO - Configuring Service(id=Default Singleton Container, type=Container, provider-id=Default Singleton Container) |
| INFO - Auto-creating a container for bean FarmerBrown: Container(type=SINGLETON, id=Default Singleton Container) |
| INFO - Configuring Service(id=Default Managed Container, type=Container, provider-id=Default Managed Container) |
| INFO - Auto-creating a container for bean org.superbiz.corn.FarmerBrownTest: Container(type=MANAGED, id=Default Managed Container) |
| INFO - Enterprise application "/Users/dblevins/examples/schedule-expression" loaded. |
| INFO - Assembling app: /Users/dblevins/examples/schedule-expression |
| INFO - Jndi(name="java:global/schedule-expression/FarmerBrown!org.superbiz.corn.FarmerBrown") |
| INFO - Jndi(name="java:global/schedule-expression/FarmerBrown") |
| INFO - Jndi(name="java:global/EjbModule481105279/org.superbiz.corn.FarmerBrownTest!org.superbiz.corn.FarmerBrownTest") |
| INFO - Jndi(name="java:global/EjbModule481105279/org.superbiz.corn.FarmerBrownTest") |
| INFO - Created Ejb(deployment-id=org.superbiz.corn.FarmerBrownTest, ejb-name=org.superbiz.corn.FarmerBrownTest, container=Default Managed Container) |
| INFO - Created Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container) |
| INFO - Started Ejb(deployment-id=org.superbiz.corn.FarmerBrownTest, ejb-name=org.superbiz.corn.FarmerBrownTest, container=Default Managed Container) |
| INFO - Started Ejb(deployment-id=FarmerBrown, ejb-name=FarmerBrown, container=Default Singleton Container) |
| INFO - Deployed Application(path=/Users/dblevins/examples/schedule-expression) |
| Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.141 sec |
| |
| Results : |
| |
| Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 |
| ---- |