Spring学习【2】Scheduling Tasks


这篇文章将完成使用Spring进行任务调度的步骤。

使用IDEA作为开发工具,使用Maven进行项目管理。


Starting with Spring Initialize

首先从Spring Initializr快速创建项目schedulingtasks,配置如下图:在这里插入图片描述
选择GENERATE下载到本地,打开项目后编辑pom.xml文件,添加依赖awaitility。

<dependency>
  <groupId>org.awaitility</groupId>
  <artifactId>awaitility</artifactId>
  <version>3.1.2</version>
  <scope>test</scope>
</dependency>

Create a Scheduled Task

在目录src/main/java/com/example/schedulingtasks/下新建ScheduledTasks.java文件。

package com.example.schedulingtasks;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

	private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

	@Scheduled(fixedRate = 5000)
	public void reportCurrentTime() {
		log.info("The time is now {}", dateFormat.format(new Date()));
	}
}

Enable Scheduling

编辑SchedulingTasksApplication.java文件。

package com.example.schedulingtasks;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {

	public static void main(String[] args) {
		SpringApplication.run(SchedulingTasksApplication.class);
	}
}

Test

运行SchedulingTasksApplication.java,可以看到控制台每隔5秒打印一次时间。
在这里插入图片描述


Summary

在这里主要对过程中用到的注解进行总结

@Scheduled
这个注解定义了某个特定的方法何时运行。
在本例中,我们使用的是fixedRate,它指定从每次方法被调用的开始时间来计算方法调用之间的间隔。同样,还有fixedDelay选项,它表示从方法完成的时间开始计算调用的间隔。@scheduled(cron="…") 是更复杂的任务调度表达式。

@EnableScheduling
这个注解确保创建了一个后台任务执行器,如果没有此注解,所有任务都不会被安排。

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值