Search code examples
spring-bootscheduled-tasksspring-scheduled

Scheduling a function in Spring boot


I am trying to schedule the following function to run every 10seconds. But it tells that it needs a void function. Is there any way to schedule the following function?

@Scheduled(fixedRate = 10000)
public FtpOutboundGateway getFiles() {
    FtpOutboundGateway gateway = new FtpOutboundGateway(sf(), "mget", "payload");
    gateway.setAutoCreateDirectory(true);
    gateway.setLocalDirectory(new File("./downloads/"));
    gateway.setFileExistsMode(FileExistsMode.REPLACE_IF_MODIFIED);
    gateway.setFilter(new AcceptOnceFileListFilter<>());
    gateway.setOutputChannelName("fileResults");
    return gateway;
}

Solution

  • For this, we need to do the following things.

    1. First put this Annotation @EnableScheduling at the class level.
    2. then at the function which needs to be scheduled should be marked with @Scheduled.
    3. The function that we are trying to schedule should not return anything.
    @EnableScheduling
    class <ClassName>{
    //def
    
     @Scheduled(fixedDelayString = "10000")
     public void fxnName() {
       //def
    }
    
    }