SpringBoot入门之定时任务

这一篇中,实现一个简单的功能:定时任务。
实现这个功能主要用到3个注解:@Component,@Scheduled,@EnableScheduling。
其中@Component表示这个类是一个组件可以被Spring容器自动检测扫描到;@Scheduled表示这个方法是个定时任务方法,同时可以配置定时参数;@EnableScheduling表示会创建后台执行器,去执行定时任务。
下面写一个小demo,每隔1秒钟打印当前的时间。

package com.spring.hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Created by zhangyi on 2017/3/30.
 */
@Component
public class ScheduledTasks {

    private static final Logger log= LoggerFactory.getLogger(ScheduledTasks.class);
    private static final SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 1000) //fixedRate这个参数表示每隔多少毫秒执行一次,1000也就是1000毫秒=1秒
    public void reportCurrentTime(){
        log.info("Current time is {}",sdf.format(new Date()));
    }
}

package com.spring;

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

/**
 * Created by zhangyi on 2017/3/29.
 */
@SpringBootApplication
@EnableScheduling
public class Application {

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

}

启动之后,就可以在控制台看到输出了,每隔1秒钟打印一次当前时间 输入图片说明

转载于:https://my.oschina.net/u/2606060/blog/876761

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值