SpringBoot定时任务


1.启动类

启动类中需要配置  @EnableScheduling

@SpringBootApplication
@EnableScheduling
public class Main {

	protected static final Logger logger = LoggerFactory.getLogger(Main.class);
	
	public static void main(String[] args) {
		logger.info("SpringBoot开始加载");
		SpringApplication.run(Main.class, args);
		logger.info("SpringBoot加载完毕");
	}

2.TestTimeService类

代码如下

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TestTimeService {

	/**
	 * 启动springboot启动后每隔两秒执行一次
	 * @author Solitary
	 */
	@Scheduled(cron = "0/2 * * * * *") //每隔两秒执行一次
	public void timer1() {
		// 获取当前时间
		LocalDateTime localDateTime = LocalDateTime.now();
		System.out.println("now time1:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
	}
	
	/**
	 * 启动springboot启动后每隔2秒运行一次
	 * @author Solitary
	 */
	@Scheduled(fixedDelay = 2000) //启动后每隔2秒运行一次
	public void timer2() {
		// 获取当前时间
		LocalDateTime localDateTime = LocalDateTime.now();
		System.out.println("now time2:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
	}
	
	/**
	 * 启动springboot后延迟10秒执行该方法,后面每隔3秒运行一次该方法
	 * @author Solitary
	 */
	@Scheduled(initialDelay = 10000,fixedRate = 3000)  //启动springboot后延迟10秒执行该方法,后面每隔3秒运行一次该方法
	public void timer(){  
	    //获取当前时间  
	    LocalDateTime localDateTime =LocalDateTime.now();  
	    System.out.println("当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));  
	}  
}


需要直接启动springboot即可





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值