spring boot 定时任务(单节点及分布式锁多节点)

【转载请注明出处】:https://www.jianshu.com/p/fe257adc331d

如果不用集群方式,不用将任务持久化,只是单节点单纯的实现定时任务的话,这种方式无疑是最快的一种,从构建项目到定时任务跑起来不会超过10分钟。

官方的demo:

git clone https://github.com/spring-guides/gs-scheduling-tasks.git

1、启用定时任务

    @SpringBootApplication
    @EnableScheduling
    public class Application {
    
     public static void main(String[] args) throws Exception {
       SpringApplication.run(Application.class);
     }
    }

加上@EnableScheduling即可开启定时任务。

2、线程池配置

@Configuration
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(20));
    }
}

3、编写定时任务类

  @Component
  public class ScheduledTasks {
  
  private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

   @Scheduled(fixedRate = 5000)
   public void reportCurrentTime() {
      log.info("The time is now {}", dateFormat.format(new Date()));
   }
  }

在定时任务类上加上注解@Component,在执行方法上加上注释@Scheduled即可启动该定时任务。

4、@Scheduled参数:

4.1 fixedRate

Execute the annotated method with a fixed period in milliseconds between invocations.

fixedRate 是两次任务的开始点的差值毫秒数,如:
@Scheduled(fixedRate=1000):从第一次开始执行的时间点算起,每隔1秒就会执行一次

4.2 fixedDelay

Execute the annotated method with a fixed period in milliseconds between the end of the last invocation and the start of the next.

fixedDelay 是上次任务结束的时间点与下次任务的开始时间点的差值毫秒数,如:
@Scheduled(fixedDelay=1000):上一次任务执行完成后等待1秒再执行下次任务

4.3 cron

@Scheduled(cron="..."):按cron规则执行,例如:

"0 0 * * * " 每个小时的0分0秒
"
/10 * * * * *" 每10秒钟
"0 0 8-10 * * *" 每天整8点、9点、10点
"0 0 6,19 * * *" 每天6点和19点整点
"0 0/30 8-10 * * *" 每天8:00, 8:30, 9:00, 9:30, 10:00 和 10:30
"0 0 9-17 * * MON-FRI" 周一到周五每天9点至17点之间的每个整点
"0 0 0 25 12 ?" 每个圣诞节午夜时分

5、多节点改造

上面只是介绍了单节点的实现方式,现在系统基本都是多节点部署的,也是为了防止单节点故障,基于当前单节点的实现方式,改造成多节点也比较简单。可以用分布式锁解决这个问题,在定时任务开始执行的时候先获取锁,只有获取成功的节点执行定时任务,没获取到锁的不执行。关于分布式锁在后面的文章中会单独讲解,这里就不介绍了。

【转载请注明出处】:https://www.jianshu.com/p/fe257adc331d

spring boot 定时任务(单节点及分布式锁多节点)_第1张图片

你可能感兴趣的:(spring boot 定时任务(单节点及分布式锁多节点))