SpringBoot定时任务(两种写法)以及集成Quartz 三种定时任务方法

今天翻翻博客发现没有定时任务的笔记,想想前两个项目都使用了定时任务,还是做一下吧。虽然很简单,但是好记性不如烂笔头。

一、springboot自己集成了定时任务,而且只需要用两个注解即可

1、在主类中添加:@EnableScheduling

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

@EnableScheduling
@SpringBootApplication
public class SpringBootWebQuartezApplication {

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

}

2、在业务方法上添加:@Scheduled(cron = "0/3 * * * * ? ")

@Service
public class EatServiceImpl implements EatService {

    @Scheduled(cron = "0/3 * * * * ? ")
    @Override
    public void eat() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sf.format(new Date());
        System.out.println(date+"开始执行");
    }
}

效果:每3秒执行一次

二、第二种方法就是自定义一个类实现 SchedulingConfigurer 接口

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

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

@Component
@Configuration
@EnableScheduling
public class Trigger implements SchedulingConfigurer {
    String time = "0/5 * * * * ?";
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        TriggerTask trigerTask = new TriggerTask(
                () -> {
                    //这里写业务方法
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date = sf.format(new Date());
                    System.out.println(date+"   张博强开始吃粑粑");
                }
                , triggerContext -> {
            System.out.println("******执行公式******{}" + time);
            //返回执行的周期
            return new CronTrigger(time).nextExecutionTime(triggerContext);
        });
        scheduledTaskRegistrar.addTriggerTask(trigerTask);
    }
}

效果:

三、集成Quartz组件

首先添加依赖:这两个依赖都可以随便用一个

        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-quartz</artifactId>-->
        <!--</dependency>-->
        <!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.1</version>
        </dependency>

然后定义配置类

import org.quartz.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QuartzConfig {
    @Bean
    public JobDetail baBa(){
        return JobBuilder.newJob(QuartzTest.class)
                .withIdentity("zhangBoQiang")//id
                .usingJobData("jiao","张博强吃BaBa工作即将开始")
                .storeDurably()
                .build();
    }

    @Bean
    public CronTrigger printTimeJiaoBabaTrigger(){
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/10 * * * * ? ");
        return TriggerBuilder.newTrigger()
                .forJob(baBa())
                .withIdentity("zhangBoQiangTrigger")
                .withSchedule(cronScheduleBuilder)
                .build();
    }
}

然后业务方法

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

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

public class QuartzTest extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String msg = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("jiao");
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"  "+msg);
        System.out.println("张博强忘我的开吃ing");
        System.out.println("赵凯劝说无用,反被踢一脚.....");
    }
}

效果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值