SpringBoot定时任务(注解方式实现+配置文件动态设置定时任务时间间隔)

一、注解方式实现

  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

启动测试 结果如下:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值