How to use Quartz Schedule in SpringBoot

Keywords: Spring

1. First, we need to introduce the dependency of Quartz.

<!--quartz-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

2. Create the Job class and inherit the QuartzJobBean, override the executeInternal() method, which is used to perform specific Job tasks.

public class WeatherDataSyncJob extends QuartzJobBean {

    private final static Logger logger=LoggerFactory.getLogger(WeatherDataSyncJob.class);

    @Autowired
    private CityDataService cityDataService;
    @Autowired
    private WeatherDataService weatherDataService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {//Actions performed
        logger.info("Weather data Sync Job start");
        //Get City ID list
        List<City> cityList=null;
        try {
            cityList=cityDataService.listCity();
        } catch (Exception e) {
            logger.error("Exception", e);
        }

        //Traverse City ID to get weather
        for(City city:cityList){
            String cityId=city.getCityId();
            logger.info("Weather Data sync job ,cityId:{}",cityId);
            weatherDataService.syncDataByCityId(cityId);
        }
        logger.info("Weather data Sync Job end");
    }
}

3. Create the configuration class of Quartz, create the JobDetail object in the configuration class, and then create the Trigger object to execute the Job in the JobDetail, and configure some parameters of the scheduled task through the SimpleScheduleBuilder object.
In the following configuration, the Job is set to execute every half hour, and the executeInternal() method is called every time.

@Configuration
public class QuartzConfiguration {

    private static final int TIME=1800;//update frequency

    //Create JobDetail
    @Bean
    public JobDetail weatherDataSyncJobDetail(){
        return JobBuilder.newJob(WeatherDataSyncJob.class)
                .withIdentity("weatherDataSyncJob")//Define the name of JobDetail
                .storeDurably().build();
    }
    //Create trigger and execute JobDetail
    @Bean
    public Trigger weatherDataSyncTrigger(){
        //Repeat every 1800 seconds
        SimpleScheduleBuilder schedBuilder=SimpleScheduleBuilder.simpleSchedule()
                .withIntervalInSeconds(TIME).repeatForever();

        return TriggerBuilder.newTrigger().forJob(weatherDataSyncJobDetail())
                .withIdentity("weatherDataSyncTrigger")//Define the name of the trigger
                .withSchedule(schedBuilder).build();
    }
}

Posted by varecha on Wed, 16 Oct 2019 08:22:16 -0700