Run Time Java Method in Time - Run Periodically

Asked

Viewed 1,878 times

2

How do I run a method of a Java class of x x in x time in Weblogic?

From what I have been checking, there is the possibility to use the @Schedule annotation in the method (Java EE 6). But since I am using Java EE 5, this annotation does not work. There is another way to do it other than with the @Schedule annotation?

1 answer

1


I have already had to do something very similar to what you are requesting. Inside the application server Weblogic 10.3 of 10 in 10 seconds connect to a JMS Topic and consume messages from this topic. I had to do this inside the Weblogic server, and I didn’t use resources directly from the Java EE platform, but from SE (Java SE).

Well, there are two ways, the first is in the Startup of its application to create a callback

or

IN the EJB you will make the call to the method you initialize, if you have one. You create a method with the annotation @Postcontruct, this method will be called as callback of the creation of its EJB.

Both in the callback from the Weblogic Startup as well as from the creation of the EJB you create a Pool with a Thread or more, which will execute your logic of accessing services or running your business methods. This Pool is a specialized pool that will periodically perform its tasks, here is the example:

public static void main(String... args){

ScheduledExecutorService scheduledExecutorService =
        Executors.newScheduledThreadPool(1);

ScheduledFuture scheduledFuture =
    scheduledExecutorService.schedule(new Callable() {
        public Object call() throws Exception {
            System.out.println("Executed!");
            return "Called!";
        }
    },
    10,
    TimeUnit.SECONDS);
}

In the above code a Pool is created with a Thread, and a task, which in this case is an instance of Callable - Running every 10 seconds.

Consider the Method shutdown

In the case of EJB, you can define a preDestroy method, which should be noted with the annotation @Predestroy - thus, you can stop the execution. For this, use the Shutdown method

scheduledExecutorService.shutdown();

This is the Executors Framework, a powerful Java Platform Framework, added in version 1.5 SE.

Please read the Class Javadocs: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

  • Thank you so much for your help Filipe. This is exactly what I wanted.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.