

十分钟!教你玩转SprintBoot定时任务
source link: https://segmentfault.com/a/1190000040391979
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

常用的定时任务有两种:
基于注解@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
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK