How to run a Timer class (always) in the deployment?

1

I have a non-web project and I'm going to turn it into a web project using Spring MVC.

Today in my method static main of my main class, I create this here:

    Exec.principalTimer = new Timer();
    Exec.principalTimer.scheduleAtFixedRate(new PrincipalTimerTask(), Exec.delay, Exec.interval);

The class PrincipalTimerTask is of type TimerTask .

How do I create this Timer in Spring already in the project deployment, without having to call any url and leave it running there, as if it were a service if I do not have a public static main in the Web container?

I can implement the WebApplicationInitializer interface and create TImer already within the onStartup method of it.

Here's where I got the idea link

    
asked by anonymous 09.05.2016 / 21:07

2 answers

1

Using EventListener can resolve your problem, but it is not ideal because it was made to perform certain action after an event in the system.

If it's Spring you can use the @ Scheduled . To enable using Schedule you need to use the @EnableScheduling annotation in your Spring configuration class.

@Configuration
@EnableScheduling
public class SpringConfig {
}

Then you should annotate a class with @Component and in the method that will execute the task you use the @Scheduled annotation.

Using fixedDelay the execution between the last execution and the next execution is fixed and one execution only starts when the other one finishes

.

@Scheduled(fixedDelay = 1000)
public void scheduleFixedDelayTask() {
    System.out.println("Fixed delay task - " + System.currentTimeMillis()/1000);
}

Using fixedRate, the next execution begins regardless of whether the last one has finished

@Scheduled(fixedRate = 1000)
public void scheduleFixedRateTask() {
    System.out.println("Fixed rate task - " + System.currentTimeMillis()/1000);
}

initialDelay, the task will be executed after the intialDelay value and then follow the fixedDelay time.

@Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void scheduleFixedRateWithInitialDelayTask() {
    long now = System.currentTimeMillis() / 1000;
    System.out.println("Fixed rate task with one second initial delay - " + now);
}

Remembering that all values are in milliseconds and you can also use cron expressions

To learn more, check out the documentation . Source: link

    
22.06.2016 / 20:01
0

The output was to create another java class annotated with @Component and create a method with that signature ..

 @EventListener
 public void onCreate(ContextRefreshedEvent e) {}

This method will run as soon as spring reads all classes ... At least that's what I understood

    
22.06.2016 / 19:17