【springboot整合quertz和task】

springboot整合quertz


提示:以下是本篇文章正文内容,下面案例可供参考

一、quertz是什么?

 Quartz是由Java开发,可以用来执行定时任务的开源框架

比如你在生活中遇到这种问题:

锻炼身体每隔半小时提醒你休息一下 

每年的情人节给暗恋女生发一封情书等等之类

二、使用步骤

1.引入库

pom依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

 自定义任务:

package com.example.demo2.quartz;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class MyQuartz extends QuartzJobBean  {
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

        System.out.println("quartz task running .....");
    }
}

Quertzconfig:

package com.example.demo2.config;


import com.example.demo2.quartz.MyQuartz;
import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuertzConfig {

    @Bean
    public JobDetail printerDetail(){
        return JobBuilder
                .newJob(MyQuartz.class)
                .storeDurably()
                .build();

    }

    @Bean
    public Trigger printJobTrigger(){
         ScheduleBuilder schedBuilder=CronScheduleBuilder.cronSchedule("0/3 * * * * ?");
        return TriggerBuilder
                .newTrigger()
                .forJob(printerDetail())
                .withSchedule(schedBuilder)
                .build();
    }
}

2.结果


2、 springboot整合task

 1.引入库

启动类加上@EnableScheduling注解

package com.example.demo2;

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

@SpringBootApplication
@EnableScheduling
public class Demo2Application {

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

}

 

 

package com.example.demo2.quartz;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledBean {
    @Scheduled(cron = "0/3 * * * * ?")
    public void printLog(){
        System.out.println(Thread.currentThread().getName()+"run....");
    }
}

 2、结果

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值