• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

spring-boot 多线程并发定时任务的解决方案

java 搞代码 4年前 (2022-01-09) 41次浏览 已收录 0个评论

刚刚看了下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));
 }
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:spring-boot 多线程并发定时任务的解决方案

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址