SpringBoot定时任务 (亲测可用)

SpringBoot定时任务


本篇文章按步骤讲如何将定时任务引入spring boot项目中,不讲原理只讲应用

第一步

在启动类(就是含有**@SpringBootApplication注解的类)上加上注解@EnableScheduling**,这样就可以使用定时任务了。

第二步

新建一个包(包名无所谓),在该包下建一个类(我命名为Jobs),在该类上加上注解@Component,就是将该类加入到spring容器中。

第三步

在Jobs中就可以定义方法了,在方法上加入注解**@Scheduled**,方法中写上你要执行的逻辑,代码如下,请忽略我的FundApi,你根据需求注入你需要的服务(Service),最后启动项目就可以了。
其中注解里面的参数请看代码中注释。

package com.byx.fund.jobs;

import com.byx.fund.api.FundApi;
import com.byx.fund.result.FundResult;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

@Component
public class Jobs {

 @Autowired
 public FundApi fundApi;

 @Scheduled(fixedDelay = 60 * 1000)//单位为毫秒,60*1000表示1分钟,表示当任务执行完毕后,一分钟后在执行。排除方法耗费的时间
 public void testTask1(){
     FundResult fundResult = fundApi.bankList(null);
     System.out.println("delay"+new Gson().toJson(fundResult));
 }

 @Scheduled(fixedRate = 60 * 1000)//单位为毫秒,60*1000表示1分钟,一分钟后在执行。包含了任务执行的耗时,如果任务用时30秒,那么次方法30秒后就执行了。
 public void testTask2(){
     FundResult fundResult = fundApi.bankList(null);
     System.out.println("rate"+new Gson().toJson(fundResult));
 }

 @Scheduled(cron = "55 09 15 * * ?")//表示15:09:55分执行(每天),详细请百度cron表达式
 public void testTask3(){
     FundResult fundResult = fundApi.bankList(null);
     Date date = new Date();
     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     String format = simpleDateFormat.format(date);
     System.out.println(format + new Gson().toJson(fundResult));
 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值