SpringBoot定时任务@EnableScheduling

一、SpringBoot定时任务schedule

1、启动类加注解@EnableScheduling开启定时任务,自动扫描。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling //开启定时任务
public class Application {

    public static void main(String[] args) {
        final SpringApplication application = new SpringApplication(com.xxx.xxx.Application.class);
        application.run(args);
    }
}

2、定时任务业务类加注解@Component被容器扫描。

3、定时执行的方法加注解@Scheduled定期执行一次。

// 定时任务业务类
@Component
public class TestTask {
	@Scheduled(fixedRate = 2000) // 两秒执行一次
	public void sum() {
		System.out.println("当前时间:" + new Date());
	}
}

二、常用定时任务配置实战

1、cron定时任务表达式:@Scheduled(cron = “0 0/1 * * * ?”) 每分钟执行一次:

@Component
public class TestTask {    
    @Scheduled(cron = "0 0/1 * * * ?")
    public void startTestTask(){
        LOG.info("=========================定时任务开始=========================");
        try{
            testTaskService.run();
        }catch (Exception e){
            e.printStackTrace();
        }
        LOG.info("=========================定时任务结束=========================");
    }
}

2、fixedRate:定时多久执行一次:

@Component
public class TestTask {
	@Scheduled(fixedRate = 2000)
	public void sum() {
		System.out.println("开始的当前时间:" + new Date());
		try {
			TimeUnit.SECONDS.sleep(4);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("结束的当前时间:" + new Date());
	}
}

运行结果:

开始的当前时间:Mon Mar 04 16:39:24 CST 2019
结束的当前时间:Mon Mar 04 16:39:28 CST 2019
开始的当前时间:Mon Mar 04 16:39:28 CST 2019
结束的当前时间:Mon Mar 04 16:39:32 CST 2019
开始的当前时间:Mon Mar 04 16:39:32 CST 2019

使用fixedRate:如果上一个任务未执行完毕,需要等待上一个任务执行完才能执行下一个任务。

3、fixedDelay:上一次执行结束时间点后几秒再次执行:

@Component
public class TestTask {
	@Scheduled(fixedDelay = 2000) 
	public void sum() {
		System.out.println("开始的当前时间:" + new Date());
		try {
			TimeUnit.SECONDS.sleep(4);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("结束的当前时间:" + new Date());
	}
}

运行结果:

开始的当前时间:Mon Mar 04 16:41:04 CST 2019
结束的当前时间:Mon Mar 04 16:41:08 CST 2019
开始的当前时间:Mon Mar 04 16:41:10 CST 2019
结束的当前时间:Mon Mar 04 16:41:14 CST 2019
开始的当前时间:Mon Mar 04 16:41:16 CST 2019

4、fixedRateString和fixedDelayString:字符串形式,可以通过配置文件指定

 

 

 

如果我的文章有帮助到您,欢迎打赏一下鼓励博主。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值