Search code examples
springcronspring-scheduled

How to log when Spring Scheduler will run


I am using cron expression for spring scheduler and the value of expression is dynamically provided by the spring bean using spel.

@Autowired
 private PurgeProperties purgeProperties;

@Scheduled(cron = "#{@purgeProperties.cronExpression}", zone = "#{@purgeProperties.zone}")
public void purgeData() throws UnknownHostException
{
           startPurge();
}

Everything is working properly only thing is I want to log when scheduler will trigger because cron expression is provided by another bean at runtime. So just want to know whether the correct expression is mapped what is been provided through file to property bean.


Solution

  • Try following code

    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.scheduling.support.CronSequenceGenerator;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.PostConstruct;
    import java.util.Date;
    
    ''''
    ''''
    @PostConstruct
    public void init() {
        CronSequenceGenerator cronTrigger = new CronSequenceGenerator(purgeProperties.cronExpression);
        Date next = cronTrigger.next(new Date());
    
        System.out.println("Next Execution Time: " + next);
    }