springboot配置scheduler定时器
1.在启动类上添加 @enablescheduling 注解
开启定时器
2.设置定时器任务(间隔和cron表达式都行)
package com.example.springboot01.config;
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.stereotype.component;
@component
public class myscheduler {
@scheduled(fixedrate = 1000) //每2秒执行一次
public void statuscheck() {
system.out.println("【*** a ***】 间隔调度");
}
@scheduled(cron="* * * * * ?") //每秒调用一次
public void removetohis() {
try {
//睡眠3秒
thread.sleep(3000);
} catch (interruptedexception e) {
e.printstacktrace();
}
system.out.println("【*** b ***】cron调度");
}
}3.配置调度池
package com.example.springboot01.config;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.annotation.schedulingconfigurer;
import org.springframework.scheduling.config.scheduledtaskregistrar;
import java.util.concurrent.executors;
/**
* 用于做并行调度使用
*/
@configuration
public class schedulerconfig implements schedulingconfigurer {
@override
public void configuretasks(scheduledtaskregistrar scheduledtaskregistrar) {
scheduledtaskregistrar.setscheduler(executors.newscheduledthreadpool(100));
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论