常用的定时任务实现
Quartz:支持单机与分布式的定时任务框架,功能十分强大,但需要额外集成
Timer:JDK自带的定时任务,功能单一
SpringSchedule:SpringBoot自带,使用方便,功能基本满足需求
创建定时任务
在SpringBoot项目中,直接使用@Scheduled
注解创建定时任务
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class LiveHeartBeatConsumer {
@Scheduled(fixedDelay = 5000)
public void test(){
System.out.println("test schedule")
}
}
其中@Scheduled
有如下属性可供配置:
cron
: Cron表达式,举几个栗子
“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秒执行
zone
: 时区,,很少使用fixedDelay
: 上一次任务执行完成后,过多久再次执行,单位msfixedDelayString
: 同fixedDelay
,参数类型为String
fixedRate
: 按一定的频率执行任务,单位msfixedRateString
: 同fixedRate
,参数类型为String
initialDelay
: 第一次执行的延迟时间,单位msinitialDelayString
: 同initialDelay
,参数类型为String
开启定时任务
在SpringBoot项目中,使用@EnableScheduling
注解开启定时任务
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author wujiawei0926@yeah.net
* @see
* @since 2020/2/10
*/
@EnableScheduling
@SpringBootApplication
public class StarterApplication {
public static void main(String[] args) throws UnknownHostException {
ConfigurableApplicationContext application = SpringApplication.run(StarterApplication.class, args);
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = env.getProperty("server.servlet.context-path");
if (path == null || "null".equals(path)) {
path = "";
}
System.out.print("\n----------------------------------------------------------\n\t" +
"Application is running! Access URLs:\n\t" +
"Local: \t\thttp://localhost:" + port + path + "/\n\t" +
"External: \thttp://" + ip + ":" + port + path + "/\n\t" +
"swagger-ui: \thttp://" + ip + ":" + port + path + "/swagger-ui.html\n\t" +
"Doc: \t\thttp://" + ip + ":" + port + path + "/doc.html\n" +
"----------------------------------------------------------");
}
}
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!