一、注解方式实现
1.启动类上一定要加注解(启用定时任务功能)
@EnableScheduling
2.新建类,如:
@Component
public class ScheduleCache {
public final static long DELAY = 60 * 1000;//定时缓存时间间隔设置
public static final Logger log = LoggerFactory.getLogger(ScheduleCache.class);
@Scheduled(fixedDelay=DELAY)
public void scheduleCache(){
log.info("------------------定时缓存任务开始执行(时间间隔为:"+DELAY/(60*1000)+"分钟)-----------------");
}
}
具体如何设置定时条件请下跳:
二、 动态时间间隔实现方式
1. 添加任务类实现TimerTask:
package com.iflytek.aisp.custom.proxy.scdx.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.TimerTask;
/**
* Created by lfx on 2019/1/9.
*/
public class PerTimerTask extends TimerTask {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void run() {
logger.info("定时任务执行中!");
}
}
2. 启动类加载定时任务
package com.iflytek.aisp.custom.proxy.scdx;
import com.iflytek.aisp.custom.proxy.scdx.service.PerTimerTask;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Timer;
/**
* Created by lfx on 2019/1/9.
*/
@SpringBootApplication
public class ApplicationStart {
private static Integer timerTaskInterval;
public ApplicationStart(@Value("${setting.interval:300}")Integer i) {
timerTaskInterval = i;
}
public static void main(String[] args) {
SpringApplication application = new SpringApplication(ApplicationStart.class);
application.run();
PerTimerTask perTimerTask = new PerTimerTask();
Timer timer = new Timer();
timer.scheduleAtFixedRate(perTimerTask,10,timerTaskInterval * 1000);
perTimerTask.run();
System.out.println("scdx proxy start success!");
}
}
3. 配置文件设置时间间隔
server:
port: 8119
setting:
#定时任务执行时间间隔 单位s 默认300s
interval: 5
启动测试 结果如下: