SpringBoot自动任务——使用Spring自带@Scheduled

参考网址

https://www.tianmaying.com/tutorial/spring-scheduling-task

要点1--定时任务上加@Scheduled注解(类上加@Component注解)

自动任务方法上加@Scheduled注解,注解后面加定时任务的定时。

/**
 * 
 * Description:定时任务示例
 *
 */
@Component
public class ScheduledTask {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Integer count0 = 1;
    private Integer count1 = 1;
    private Integer count2 = 1;

    /**
     * 
     * Description:表示每隔5000ms,Spring scheduling会调用一次该方法,不论该方法的执行时间是多少
     * @throws InterruptedException
     */
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() throws InterruptedException {
        System.out.println(String.format("---第%s次执行,当前时间为:%s", count0++, dateFormat.format(new Date())));
    }

    /**
     * 
     * Description:表示当方法执行完毕5000ms后,Spring scheduling会再次调用该方法
     * @throws InterruptedException
     */
    @Scheduled(fixedDelay = 5000)
    public void reportCurrentTimeAfterSleep() throws InterruptedException {
        System.out.println(String.format("===第%s次执行,当前时间为:%s", count1++, dateFormat.format(new Date())));
    }

    //一种通用的定时任务表达式,这里表示每隔5秒执行一次
    @Scheduled(cron = "*/5 * * * * * *")
    public void reportCurrentTimeCron() throws InterruptedException {
        System.out.println(String.format("+++第%s次执行,当前时间为:%s", count2++, dateFormat.format(new Date())));
    }

}

要点2--几种定时的表示方法

在@Scheduled注解中,我们使用了三种方式来实现了同一个功能:每隔5秒钟记录一次当前的时间:

fixedRate = 5000表示每隔5000ms,Spring scheduling会调用一次该方法,不论该方法的执行时间是多少。

fixedDelay = 5000表示当方法执行完毕5000ms后,Spring scheduling会再次调用该方法。

cron = "*/5 * * * * * *"提供了一种通用的定时任务表达式,这里表示每隔5秒执行一次。

要点3--main方法上加@EnableScheduling注解

main上加@EnableScheduling注解,说明要开启SpringBoot的自动任务。

@EnableScheduling 注解的作用是发现注解@Scheduled的任务并后台执行。

@RestController
@SpringBootApplication(exclude = SpringDataWebAutoConfiguration.class)
@EnableScheduling
public class RuicheServerJSP {
	
	@RequestMapping("/")
	String index(){
		return "Hello Spring Boot";
	}

	public static void main(String[] args){
		SpringApplication.run(RuicheServerJSP.class, args);
	}
}

★@Scheduled中cron一些常用的表达式

"0 0 12 * * ?"    每天中午十二点触发

"0 15 10 ? * *"    每天早上10:15触发

"0 15 10 * * ?"    每天早上10:15触发

"0 15 10 * * ? *"    每天早上10:15触发 

转载于:https://my.oschina.net/u/3866531/blog/1829105

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值