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

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 !");
}
}
复制代码

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

后记

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

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

小结

获取微服务、分布式、高并发、高可用,性能优化丶Mysql源码分析等等一些技术资料

最后,每一位读到这里的Java程序猿朋友们,感谢你们能耐心地看完。希望在成为一名更优秀的Java程序猿的道路上,我们可以一起学习、一起进步!都能赢取白富美,走向架构师的人生巅峰!

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


分享到:


相關文章: