springboot整合定时任务(相对于Quartz和Task等框架非常简单)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/uniqueweimeijun/article/details/84188860

最近真正用springboot整合定时任务发现其流程灰常简单,进一步突出了springboot的强大之处。相对于之前用过的quartz和task来说可以说是简单爆了,尤其是quartz整合spirng的时候那配置简直是日了动物园了。废话不说直接怼代码。

package com.example.demo;

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

//下边这个注解可以不加,可以在任务类上边加上也可以起到同样的作用
@EnableScheduling

@SpringBootApplication
public class SpringbootApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootApplication.class, args);
	}
}
package com.example.demo;

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

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Configurable
//如果启动类上加上了下边这个注解在这里就不要再加了。当然加了也不会报错(亲测)这里我给注释掉了
//@EnableScheduling
public class ScheduleTask {
	//这里的cron表达式意思是每隔10秒执行一次
	@Scheduled(cron = "0/10 * * * * ? ")
	public void reportCurrentTime() {
		System.err.println("scheduling111 tasks example By corn  the time is now:" + dateFormat().format(new Date()));
	}

	public SimpleDateFormat dateFormat() {
		return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	}

}

在这里推荐一个关于cron表达式的网站,可以直接根据自己的需要来生成cron表达式。

cron表达式生成器

最后如果您需要了解传统的quartz定时框架,可以看一下我之前写的两篇博客。

quartz核心知识

quartz从入门到实战

如果不嫌弃可以给博主点个赞吧,不嫌弃的话加个关注以此来共同学习。it嘛注定就在bug和新技术上游荡。哈哈~~~~~~

猜你喜欢

转载自blog.csdn.net/uniqueweimeijun/article/details/84188860