Java Spring Extender @Scheduled to read a file

Asked

Viewed 446 times

3

I have tasks to do as soon as I top up my application, they run over and over again that way:

  @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 didn’t want to have to stop the application every time to do this. So I was wondering if there’s a way to extend the @Scheduled spring to read some configuration file, it’s like?

2 answers

1


You can parameterize the Spring Annotation, it is a little different the parameter:

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

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

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

Ai just add the property to your configuration file.

Source: http://www.baeldung.com/spring-scheduled-tasks

  • I’ll try over the weekend, if you funfar your answer.

  • Didn’t work?!

  • scheduled Union for Windows ?

0

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

@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 Quartz support, but Quartz is a cannon if its application has no real need to Jobs persistent / transactional / distributed.


Sources:

  1. Spring Framework Reference - Task Execution and Scheduling
  2. Soen - Creating Spring Framework task programmatically?
  3. Soen - How to Cancel Spring timer Execution
  4. Spring Scheduling: @Scheduled vs Quartz

Browser other questions tagged

You are not signed in. Login or sign up in order to post.