Spring boot 定时任务

Spring boot 定时任务

说到定时任务呢,大家应该都很熟悉了,其实定时任务这块确实使用起来没太大变化,主要在spring boot中使用定时任务时需要在启动时将定时任务开启,具体的定时任务实现类添加注解即可,详细说明如下:

1.在启动类中需要添加一个类注释:@EnableScheduling;

2.在job的实现类中添加类注释:@Component和方法注释:@Scheduled(cron="0/10 * * * * ?")

就是这么简单,具体代码如下:

package com.zxl.examples.job;

import com.zxl.examples.service.UserSerivceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 2017/7/27.
 */
@Component
public class UserJob {

    @Autowired
    UserSerivceImpl userSerivce;

    @Scheduled(cron="0/10 * * * * ?")
    private void printSomething(){
        System.out.println("------------------------------this is a test job");
    }

    @Scheduled(cron="0/10 * * * * ?")
    private void callService(){
        System.out.println("###############################this is a test job,the call service method value is : "
                +userSerivce.canCache());
    }

    @Scheduled(fixedRate = 10000)
    private void printSomething2(){
        System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^this is a test job2");
    }
}


小提示:@Scheduled 参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?",一种是 fixedRate = 6000,两种都表示每隔六秒打印一下内容。
fixedRate 说明
  ● @Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行
  ● @Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行
  ● @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JAVA小男子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值