刚刚看了下Spring Boot实现定时任务的文章,感觉还不错。Spring Boot 使用Spring自带的Schedule来实现定时任务变得非常简单和方便。在这里个大家分享下。
开启缓存注解
@SpringBootApplication @EnableScheduling //开启定时任务 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
编写定时任务
@Component<strong>本文来源gaodai#ma#com搞@@代~&码*网2</strong> public class ScheduledTasks { private Logger logger = LoggerFactory.getLogger(ScheduledTasks.class); // cron接受cron表达式,根据cron表达式确定定时规则 @Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次 public void testCron() { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); logger.info(sdf.format(new Date())+"*********每5秒执行一次"); } }
任务完成
启动项目,查看控制台打印信息,发现定时任务已经生效。spring boot 和Scheduled整合完毕。
存在问题
但是后来发现个问题,通过同时测试几个任务发现,所有的任务都是在同一个线程池中的同一个线程来完成的。在实际开发过程中,我们当然不希望所有的任务都运行在一个线程中。
@Scheduled(cron="0/1 * * * * ? ") //每1秒执行一次 public void testCron1() { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); logger.info(sdf.format(new Date())+"*********每1秒执行一次"); } @Scheduled(cron="0/2 * * * * ? ") //每2秒执行一次 public void testCron2() { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); logger.info(sdf.format(new Date())+"*********每2秒执行一次"); } @Scheduled(cron="0/3 * * * * ? ") //每3秒执行一次 public void testCron3() { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); logger.info(sdf.format(new Date())+"*********每3秒执行一次"); } @Scheduled(cron="0/4 * * * * ? ") //每4秒执行一次 public void testCron4() { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); logger.info(sdf.format(new Date())+"*********每4秒执行一次"); }
解决方案
那么,怎么设计成多线程实现并发呢?在网上看到过这样的解决方案。通过ScheduleConfig配置文件实现SchedulingConfigurer接口,并重写setSchedulerfang方法,我们尝试着配置了一下。
@Configuration public class ScheduleConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5)); } }