SpringBoot(一) 添加定时任务

ps: 在我们的项目开发过程中,经常需要定时任务来帮助我们来做一些内容,springboot默认已经帮我们实行了,只需要添加相应的注解就可以实现

一.构建项目,如图所示:

    

 创建一个用于执行定时任务的接口,以及一个接口的实现类。

二.添加注解

      在启动类添加定时注解 @EnableScheduling

     

在实现类添加定时任务,哪个方法需要执行定时任务,则添加到哪个方法上。

import com.example.smalserver.http.service.server.TimingService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @Author: caohuijie
 * @Date: 创建日期 2018/11/7
 * @Modified By:
 * @Description: 定时任务类
 */
@Component
@Service
public class TimingServiceImpl implements TimingService {

    private int count=0;

    @Scheduled(cron="*/6 * * * * ?")
    @Override
    public void timingTask() {
        System.out.println("this is scheduler task runing  "+(count++));
    }
}

 或者:

import com.example.smalserver.http.service.server.TimingService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * @Author: caohuijie
 * @Date: 创建日期 2018/11/7
 * @Modified By:
 * @Description: 定时任务类
 */
@Service
public class TimingServiceImpl implements TimingService {

    private int count=0;

    @Scheduled(cron="*/6 * * * * ?")
    @Override
    public void timingTask() {
        System.out.println("this is scheduler task runing  "+(count++));
    }
}

corn表达式:

"0 0 * * * *" 表示每小时0分0秒执行一次

" */10 * * * * *" 表示每10秒执行一次

"0 0 8-10 * * *" 表示每天8,9,10点执行

"0 0/30 8-10 * * *" 表示每天8点到10点,每半小时执行

"0 0 9-17 * * MON-FRI" 表示每周一至周五,9点到17点的0分0秒执行

"0 0 0 25 12 ?" 表示每年圣诞节(12月25日)0时0分0秒执行

 

    

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值