在我们的项目开发过程中,经常需要定时任务来帮助我们来做一些内容,springboot默认已经帮我们实行了,只需要添加相应的注解就可以优雅的实现。对于一些简单的任务调度,这是一种非常简便的方式。
项目依赖
<parent>
<groupId>org.spring work.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
<de ion>
https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/htmlsingle/
</de ion>
<modelVersion>4.0.0</modelVersion>
<artifactId>demo-springboot-schedule</artifactId>
<dependencies>
<dependency>
<groupId>org.spring work.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.spring work.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
编写定时任务
package top.yuyufeng.demo.schedule;
import org.spring work.scheduling.annotation.Scheduled;
import org.spring work.stereotype.Component;
import java.util.Date;
/**
* @author yuyufeng
* @date 2018/12/21.
*/
@Component
public class MySchedule {
/**
* 每5秒钟打印一次时间
*/
@Scheduled(cron = \"*/5 * * * * ?\")
public void printDatetime() {
System.out.println(new Date());
}
}
//some examples
//每隔5秒执行一次:*/5 * * * * ?
//每隔1分钟执行一次:0 */1 * * * ?
//每天23点执行一次:0 0 23 * * ?
//每天凌晨1点执行一次:0 0 1 * * ?
//每月1号凌晨1点执行一次:0 0 1 1 * ?
//每月最后一天23点执行一次:0 0 23 L * ?
//每周星期天凌晨1点实行一次:0 0 1 ? * L
//在26分、29分、33分执行一次:0 26,29,33 * * * ?
//每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?
运行
package top.yuyufeng.demo;
import org.spring work.boot.SpringApplication;
import org.spring work.boot.autoconfigure.SpringBootApplication;
/**
* @author yuyufeng
* @date 2018/12/21.
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
线程池的配置
在项目中,可以多线程(并行),提高效率
package top.yuyufeng.demo.config;
import org.spring work.context.annotation.Bean;
import org.spring work.context.annotation.Configuration;
import org.spring work.scheduling.TaskScheduler;
import org.spring work.scheduling.annotation.EnableScheduling;
import org.spring work.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
* @author yuyufeng
* @date 2018/12/10.
*/
@Configuration
@EnableScheduling
public class SchedulerConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
//线程池大小
scheduler.setPoolSize(5);
//线程名字前缀
scheduler.setThreadNamePrefix(\"spring-task-thread\");
return scheduler;
}
}
fixedRate 说明
@Scheduled 参数可以接受两种定时的设置,一种是我们常用的cron=\"*/6 * * * * ?\",一种是 fixedRate = 6000,两种都表示每隔六秒打印一下内容。
- @Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行
- @Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行
- @Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次
继续阅读与本文标签相同的文章
下一篇 :
社群之道术器
-
《Apache Kafka实战》| 每日读本书
2026-05-18栏目: 教程
-
为什么它有典型FaaS能力,却是非典型FaaS架构? | 开发者必读(065期)
2026-05-18栏目: 教程
-
Mybatis执行SQL的4大基础组件详解
2026-05-18栏目: 教程
-
Java描述设计模式(08):桥接模式
2026-05-18栏目: 教程
-
Java描述设计模式(09):装饰模式
2026-05-18栏目: 教程
