SpringBoot通过注解的方式调用Quartz定时任务

1.引入Quartz依赖
在这里插入图片描述
2.SpringBoot启动类增加@EnableScheduling注解
在这里插入图片描述
3.创建一个定时任务工作类在方法,代码如下:

package com.jlzh.lftwebservice.service.quartz;

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

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

/**
 * @ClassName: QuartzJob
 * @ Description: 定时任务类
 * @author:
 * @date:2022/11/02
 */
@Component
public class QuartzJob{

    @Scheduled(cron = "0/5 * * * * ? ")
    protected void executeInternal() throws JobExecutionException {
        String time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        System.out.println(time + "===> 正在工作。。。");
    }
}

此时要注意的是定时任务所在的类要交给Spring容器管理,最简单的就是在类上增加@Component注释。定时任务工作方法上增加@Scheduled(cron = "0/5 * * * * ? ")注释表示任务每5秒执行一次。
4.执行结果如截图所示:
在这里插入图片描述
5.cron的值也可以通过外部配置文件的形式指定,代码如下:

package com.jlzh.lftwebservice.service.quartz;

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

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

/**
 * @ClassName: QuartzJob
 * @ Description: 定时任务类
 * @author:
 * @date:2022/11/02
 */
@Component
public class QuartzJob{

    @Scheduled(cron = "${cron.exp}")
    protected void executeInternal() throws JobExecutionException {
        String time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
        System.out.println(time + "===> 正在工作。。。");
    }
}

然后在在配置文件application.yml中填写配置变量的值,此种方式比较灵活,不用修改代码即可更改时间。而且如果将值改为"-“,代表定时任务无效。
在这里插入图片描述
值改为”-”后代表定时任务无效,直接使用"-”会标红,可以那单引号引一下即可
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值