Java Spring Extender @Scheduled to read a file

3

I have tasks to do as soon as I upload my application, they are executed repeatedly like this:

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

But sometimes I need to update the time interval and I did not want to have to stop the application every time to do this. So I was wondering if there is a way to extend Spring's @Scheduled so that it reads some configuration file, how?

    
asked by anonymous 02.07.2016 / 14:35

2 answers

1

You can parameterize the Spring annotation, the parameter is a bit different:

//fixedDelay task:
@Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds}")

//fixedRate task:
@Scheduled(fixedRateString = "${fixedRate.in.milliseconds}")

//A cron expression based task:
@Scheduled(cron = "${cron.expression}")

Just add the property to your configuration file.

Source: link

    
16.08.2016 / 20:48
0

Updating Spring properties with the running application is often a non-trivial problem. This way it is often easier to implement this type of scheduling programmatically:

@Autowired private TaskScheduler scheduler; 

private ScheduledFuture scheduledTask;

@PostConstruct
public void init() throws Exception {
    // Dispara com valor padrao, alternativamente 
    // isso pode ser lido do arquivo de propriedades
    scheduleFixedRateTask(10000L);
}

public void scheduleFixedRateTask(final long rate) {
    if (scheduledTask!= null) {
        // Em um código real você provavelmente quer fazer algo mais robusto
        // do que interromper a tarefa logo de cara.
        scheduledTask.cancel(true);
    } 
    Runnable task = new Runnable() {
       public void run() {
          System.out.println("Fixed rate task - " + System.currentTimeMillis()/rate);
       }
    };
    scheduledTask= scheduler.scheduleWithFixedDelay(task, rate);
}

For more complex use cases Spring has support for Quartz , but Quartz is a cannon if your application has no real need for jobs persistent / transactional / distributed.

Fonts :

  • Spring Framework Reference - Task Execution and Scheduling
  • SOen - Creating Spring Framework task programmatically?
  • SOen - How to cancel Spring timer execution
  • Spring Scheduling: @Scheduled vs. Quartz
  • 20.08.2016 / 20:52