业务逻辑层
@Component @EnableScheduling public class MyFirstJob implements SchedulerObjectInterface{ private static final Logger log = Logger.getLogger(MyFirstJob.class); //默认晚上12点 private String cron="0 00 00 * * ?"; public static ThreadPoolTaskScheduler scheduler; static { scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(10); scheduler.initialize(); } private static ScheduledFuture future; @Bean public TaskScheduler scheduler() { return new ThreadPoolTaskScheduler(); } @Override @PostConstruct public void start() { log.info("进入start方法"); future = scheduler.schedule(new Runnable() { @Override public void run() { System.out.println( " Hello World! " + new Date()); } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { String cron = getCron(); System.out.println("cron++++"+cron); CronTrigger trigger = new CronTrigger(cron); return trigger.nextExecutionTime(triggerContext); } }); } @Override public void stop() { future.cancel(false); } //可以前端传值 通过set方法动态修改 public String getCron() { return cron; } public void setCron(String cron) { this.cron = cron; } // 可以从数据集读取cron表达式 // private String cronConfig() { // try { // Thread.currentThread().sleep(1000*10); // } catch (InterruptedException e) { // e.printStackTrace(); // } // String tempReportSendHour = quartzMapper.queryByKey("report_sendhour"); // String reportSendHour=""; // if(tempReportSendHour.startsWith("0")){ // reportSendHour = tempReportSendHour.substring(1); // }else { // reportSendHour = tempReportSendHour; // } // if(reportSendHour!=null&&!"".equals(reportSendHour)&&!"null".equalsIgnoreCase(reportSendHour)){ // cron = "0 */" + reportSendHour + " * * * ?"; // } // log.info("查询cron"+cron); // return cron; // } }
接口Dao
public interface SchedulerObjectInterface { void start(); void stop(); }