SpringBoot + Scheduling(定时任务)

34 篇文章 0 订阅
14 篇文章 0 订阅

SpringBoot + Scheduling(定时任务)

  • 完成简单的定时任务,SpringBoot框架实现
  • @Scheduled注解式(cron语言,fixedDelay或者间隔时间)
  • 基于SchedulingConfigurer接口实现

一、@Scheduled注解式

@Component被spring管理;@EnableScheduling开启定时任务;@Configuration开启配置;@Scheduled方法执行时间;@async如果配置了线程池 , 可以开启异步执行,但是方法需要公有化 ‘public’。

  • application.yml 配置变量
job:
  task2:  0/15 * * * * ?
  •  方法配置

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
@Configuration
public class QutrzConfig {

    /**
     * 如果配置了线程池 , 可以开启异步执行
     * 但是方法需要公有化 ‘public’
     */
//    @Async
    @Scheduled (cron = "0/5 * * * * ?")
    private void task (){
        System.out.println("爱我中华!");
    }

    @Scheduled (cron = "${job.task2}")
    private void task2 (){
        System.out.println("中华崛起!");
    }
}
  • 执行结果

 一、SchedulingConfigurer接口式

@Component被spring管理;@EnableScheduling开启定时任务;@Configuration开启配置。

  • 方法配置


import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;


@Component
@EnableScheduling
@Configuration
public class QutrzConfig2 implements SchedulingConfigurer {

    private String getCron (){
        //可以通过不同的方式获取执行时间
        return "0/10 * * * * ?";
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> {
                    System.out.println("奋青!");
                },
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    String cron = this.getCron();
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );

    }
}
  • 执行结果

chenyb 随笔记录,方便学习

2020-09-21

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值