本篇文章按步骤讲如何将定时任务引入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));
}
}