【springboot学习】@Scheduled集成quartz

springboot使用@Scheduled注解集成quartz

上一篇我们通过装配quartz的调度器、触发器、任务实现了定时任务,本篇我们将使用@Scheduled注解更简单的实现定时任务

SpringBoot集成Quartz步骤

第一步,引入依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.3</version>
</dependency>
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz-jobs</artifactId>
    <version>2.2.3</version>
</dependency>

第二步骤:给定时任务方式添加@Scheduled注解

@Component
public class PrintTask {

	private Logger log = LoggerFactory.getLogger(PrintTask.class);

	@Scheduled(cron = "0/2 * * * * ?")
	public void print() {
		log.info("hello world!");
	}

}

@Component注解是为了让spring发现该任务,当然@service、@controller也可以。

这里重点说一下@Scheduled注解

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {

	// cron表达式
	String cron() default "";

    // 指定时区,默认为空(将使用服务器的本地时区)
	String zone() default "";

    // 上一次任务执行结束到下一次开始之间的时间间隔
	long fixedDelay() default -1;

    // 上一次任务执行结束到下一次开始之间的时间间隔
	String fixedDelayString() default "";

    // 任务执行的频率
	long fixedRate() default -1;

    // 任务执行的频率
	String fixedRateString() default "";
    
    // 延迟多久第一次执行任务
	long initialDelay() default -1;

    // 延迟多久第一次执行任务
	String initialDelayString() default "";

}

第三步骤:给WebApplication添加@EnableScheduling注解,启动定时任务.

@SpringBootApplication
@EnableScheduling
public class HelloWebApplication {

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

然后启动程序,就发现定时任务启动了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值