import com.patient.core.adapter.CorsFilter;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableScheduling//开启定时任务注解
@SpringBootApplication
@MapperScan("com.patient.core.mapper")
public class PatientSystemApplication {
public static void main(String[] args) {
SpringApplication.run(PatientSystemApplication.class, args);
}
@Bean
public FilterRegistrationBean setFilter() {
FilterRegistrationBean filterBean = new FilterRegistrationBean();
filterBean.setFilter(new CorsFilter());
filterBean.setName("CorsFilter");
filterBean.addUrlPatterns("/*");
return filterBean;
}
}
import com.patient.core.service.UserService; import com.patient.core.util.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.support.CronTrigger; import java.util.Date; @Configuration public class ReminderTask implements SchedulingConfigurer { private static Logger log = LoggerFactory.getLogger(ReminderTask.class); @Autowired private UserService userService;
//项目启动会自动执行该Controller 类,首先执行触发器的方法,查询要执行业务逻辑的时间(需要转换成Cron表达式),动态的执行业务逻辑,业务逻辑执行完毕会再次执行触发器 设定下次执行时间
@Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { scheduledTaskRegistrar.addTriggerTask(doTask(), getTrigger()); } // 业务执行方法 private Runnable doTask() { return new Runnable() { @Override public void run() { try { //业务逻辑 log.info("业务执行方法"); } catch (Exception e) { e.printStackTrace(); } } }; } //业务触发器 private Trigger getTrigger() { return new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { String dateStr = userService.getLastTime(); if ("".equals(dateStr) || dateStr == null) return null; String cron = DateUtils.getCron(DateUtils.strToDateLong(dateStr)); //定时任务触发,可修改定时任务的执行周期 CronTrigger trigger = new CronTrigger(cron); Date nextExecDate = trigger.nextExecutionTime(triggerContext); log.info("业务触发器:"+DateUtils.dateToStrLong(nextExecDate)); return nextExecDate; } }; }