SpringBoot定时任务,总有一款适合你

前言

  定时任务可以帮我们在给定的时间内处理任务,比如你的闹钟会在每天早上教你起床呀,比如每天凌晨读取你在公司人员表里的就职状态,如果为离职,就定时一个月后自动删库啊(开个玩笑),等等,下面就介绍三种定时任务的创建方法(其实是两种,第三种不算)。

三种方式

使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式:

  • 基于注解(@Scheduled)
  • 基于接口(SchedulingConfigurer) 前者相信大家都很熟悉,但是实际使用中我们往往想从数据库中读取指定时间来动态执行定时任务,这时候基于接口的定时任务就派上用场了。
  • 基于注解设定多线程定时任务

基于 @Scheduled 注解

@Configuration将该类标记为配置类,自动注入。@EnableScheduling 开启定时任务。

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

/**
 * @author: zp
 * @Date: 2019-09-28 17:08
 * @Description:
 */
@Configuration
@EnableScheduling
public class TaskBasedAnnotation {

    // 每两秒执行一次
    @Scheduled(cron = "*/2 * * * * ?")
    public void sayHello(){
        System.out.println("Hello, menmen!"+Thread.currentThread().getName());
    }

}
复制代码

基于SchedulingConfigurer接口

import com.example.demojpa.dao.CronRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

/**
 * @author: zp
 * @Date: 2019-09-28 17:33
 * @Description:
 */
@Configuration
@EnableScheduling
public class TaskBasedInterface implements SchedulingConfigurer {

    /**
     * 这是JPA,Mapper可以注入Mapper文件
     * 都是为了从数据库读取配置 *3 * * * * ?
     */
    @Autowired
    CronRepository cronRepository;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addCronTask(()-> System.out.println("你好,门门!"+Thread.currentThread().getName()),cronRepository.getCron());
    }

}
复制代码

异步定时任务

@EnableAsync开启多线程。@Async标记其为一个异步任务。

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

/**
 * @author: zp
 * @Date: 2019-09-28 17:50
 * @Description:
 */
@Configuration
@EnableScheduling
@EnableAsync
public class AsyncTask {

    @Async
    @Scheduled(cron = "*/4 * * * * ?")
    public void message(){
        System.out.println("menmen ni hao !");
    }
}复制代码

file

可以看到每次的线程都不一样。可以用来执行比较耗时的任务。

后记

  学这个的目的主要是想在数据库里存上几千条臭美的话,然后结合某个短信平台每天早上随机发我一条,这样的话肯定每天都高兴的要死~file

猜你喜欢

转载自juejin.im/post/5d9d7fc5e51d457805049722
今日推荐