关于java:十分钟教你玩转SprintBoot定时任务

4次阅读

共计 1767 个字符,预计需要花费 5 分钟才能阅读完成。

罕用的定时工作有两种:

  1. 基于注解
  2. 基于接口

基于注解 @Scheduled


@Service
public class Scheduling1Service {// 每 2 秒执行一次(若上次工作执行工夫超过 2 秒,则立刻执行,否则从上一个工作开始时算起 2 秒后执行本次工作)
    @Scheduled(fixedRate = 2000)
    public void test1() throws InterruptedException {Thread.sleep(1000L);// 模仿定时工作执行消耗了 1s
        Thread.sleep(3000L);// 模仿定时工作执行消耗了 3s
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test1 is called");
    }

    // 上一个工作执行完 2 秒后,再执行本次工作
    @Scheduled(fixedDelay = 2000)
    public void test2() throws InterruptedException {Thread.sleep(3000L);// 模仿定时工作执行消耗了 3s
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test2 is called");
    }

    // 反对 corn 表达式
    @Scheduled(cron = "0 0 1 * * ?")// 每天凌晨 1 点执行
    public void test3() throws InterruptedException {Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(date)+"==>SchedulingService.test3 is called");
    }
}

注:不会写 corn 表达式的小伙伴,能够应用这个哦:https://cron.qqe2.com 会帮你主动生成 corn 表达式,且能检测你的表达式是否非法。十分好用!

以上三种是应用频次比拟多的。因为不承受参数,次要用户定时同步第三方根底数据的业务场景。

应用 @Scheduled 需在 pom 中援用 springboot 的相干依赖,并在 Application 主入口函数中减少 @EnableScheduling 的注解。

基于接口模式的定时工作

基于注解的形式的工作配置起来很简略也很好用,然而因为不能传递参数,应用场景无限。那么就须要应用基于接口模式的定时工作了。

增加依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
@Service
public class Scheduling3Service implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Runnable() {
                    @Override
                    public void run() {System.out.println("cccccccc");
                    }
                },
                triggerContext -> {return new CronTrigger("0/1 * * * * ?").nextExecutionTime(triggerContext);
                }
        );
    }
}

以上就是两种罕用的定时工作,小伙伴们,你,学废了吗?

更多 java 原创浏览:https://javawu.com

正文完
 0