Java Web Application Task that runs from time to time

0

I am developing a Java Web application in which I have to make some tasks run every certain time, one of them is to calculate a few hours of a loan made (which is stored in database), if this loan already has the number of hours elapsed since its creation, a task must be done such as inserting data in another table, notifying the user, etc.

This is the first time I have to do something like this on Java Web and since I have no idea for it (or at least it is optimal and safe), I know that there is the Timer and TimerTask

I tried the following:

@Stateless
public class LoanBean{

    Timer timer;

    public LoanBean() {
        checkLoans();
    }

    public void checkLoans() {
        timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("Tarea ejecutándose");
            }
        };

        timer.schedule(task, 10, 1000);
    }

}

It seems to work well in that from time to time the task is executed but only when interacting with this EJB, the idea is to run it when the application is mounted on the application server because if the task is restarted and it does not run until you return to interact with this EJB (open the page in the web browser), in this case I use Oracle WebLogic as an application server

    
asked by edwin22 05.07.2017 в 18:05
source

2 answers

0

For what you mention, you should use something like Quartz

    
answered by 05.07.2017 в 18:18
0

You can use Spring itself through the @Scheduled annotation:

An Example by java config:

   @Scheduled(fixedDelay = SEGUNDOS_TAREA_MENSAJE)
   public void tareaProgramada() {
       // Aqui pondrías el código que ejecutaras cada SEGUNDOS_TAREA_MENSAJE segundos

       LOG.info("Me Ejecuto Cada "
           .concat(String.valueOf(SEGUNDOS_TAREA_MENSAJE/1000))
           .concat(" Segundos Mostrándote: ")
           .concat(new Date().toString()));
    }

Here you have more information about @Schedule Schedule Documentation

    
answered by 05.07.2017 в 18:25