Search code examples
javaspringmavencron

Configure a scheduled task on .war file created by Spring/Maven


I have an application developed on spring framework with maven. I have many modules (each one has its own pom.xml file) and I have the generic pom.xml to compile the entire project.

Using maven I compile a .war file and I deploy this one in a Jetty server, but now I have another problem. I need to configure a function that will execute some code every couple of minutes. I tried to configure it like at the following link, so having:

I edited the specific pom.xml file and I add this:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
  <version>1.2.1.RELEASE</version>
</dependency>

On dependencies list, I added this in plugin list:

<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

I created in the same module one file that defined this class:

@Component
public class ScheduledTasks {
  private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedDelay = 5000)
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

but it doesn't work for me. Logs don't print anything. I've been struggling with this issue for a while but I didn't manage to find any solution also taking a look at other related Q/A on StackOverflow.

What Am I doing wrong? How can I fix this?

Thanks in advance.


Solution

  • You should fix by replacing @Component with @Service and @EnableScheduling.

    @Service
    @EnableScheduling
    public class ScheduledTasks {
        . . .
    }