简体   繁体   中英

A better way to run task periodically in Java

I have a method that I want to be invoked periodically: every day on 11 am. It is a simple method in Main:

public void loadProduct() {
PropertyConfigurator.configure("log4j.properties");
try {
     service.create(product);
     logger.info("Creation started");
} catch (Exception e) {
  // Log Exception
     logger.error(e);
}
}

I have almost figured out how to achieve this with the help of Spring context:

<task:scheduler id="scheduler" pool-size="1"/>

<task:scheduled-tasks scheduler="scheduler">
    <task:scheduled ref="productTask" method="loadProduct" cron="0/30 * * * * *"/>
</task:scheduled-tasks>

But how to schedule the task to start every 24 hours on 11 am every day?

Or is there a way to achieve this in Java code?

But how to schedule the task to start every 24 hours on 11 am every day?

This can be achieved by using the cron expression: 0 0 11 * * * .

Or is there a way to achieve this in Java code?

Yes, by using the Scheduled (Spring Framework 5.0.1.RELEASE API) annotation, for example:

@Scheduled(cron = "0 0 11 * * *", zone = "Europe/Moscow")
public void run() {
    // ...
}

Additional references:

  1. Integration: 7. Task Execution and Scheduling: 7.4. Annotation Support for Scheduling and Asynchronous Execution, Spring Framework Documentation .
  2. Getting Started · Scheduling Tasks .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM