First define an ApplicationgWareUtils
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class ApplicationContextAwareUtil implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // TODO Auto-generated method stub ApplicationContextAwareUtil.context = applicationContext; } public static Object getBean(String beanName) { return context==null?null:context.getBean(beanName); } public static <T> T getBean(Class<T> requiredType) { return context==null?null:context.getBean(requiredType); } public static String[] getBeanDefinitionNames() { return context.getBeanDefinitionNames(); } }
Introduce the following maven dependencies
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> <version>2.2.1</version> </dependency>
Add time to execute cron expression in application.properties in the resource directory
#Control the time of resource monitoring. The cron expression here means that 0 0 9 is executed at 9:00 every day? * * resource_monitro.cron = 5 * * * * *
Write a timer
@Component public class ResourceUseMonitorTask implements Job { @Value("${resource_monitro.cron}") private String time; public String getTime() { return time; } public void setTime(String time) { this.time = time; } public static void jobStart() { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>:" + ApplicationContextAwareUtil.getBean(ResourceUseMonitorTask.class).getTime()); JobDetail jobDetail = JobBuilder.newJob(ResourceUseMonitorTask.class).withIdentity("resource_monitor_job", "resource_monitor_group").build(); //The task execution rule is specified here Trigger trigger = TriggerBuilder.newTrigger().withIdentity("resource_monitor_trigger", "resource_monitor_trigger_group").startNow()// .withSchedule(CronScheduleBuilder.cronSchedule(ApplicationContextAwareUtil.getBean(ResourceUseMonitorTask.class).getTime())).build(); SchedulerFactory sf = new StdSchedulerFactory(); Scheduler scheduler = null; try { scheduler = sf.getScheduler(); scheduler.scheduleJob(jobDetail, trigger); scheduler.start(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { // perform the desired operation here } }