SpringBoot定时任务

14 篇文章 0 订阅
11 篇文章 0 订阅

        定时任务一般是项目中都需要用到的,可以用于定时处理一些特殊的任务,比如定时发送短信,邮件等等今天我们就来看下在SpringBoot中如何集成定时任务。

        首先,搭建好一个springboot项目,可使用maven或者gradle或者其他。由于这里讲的是主要是定时任务,没有搭建过springboot项目的可以参考https://blog.csdn.net/qq_34996727/article/details/65437616

1.静态定时任务

        首先定时器需要有一个总开关,因为我可能要定时很多函数,如果我想全都暂时关上总不能一个一个把注解给删掉吧。所以我们需要先把总开关打开,也就是在springboot的入口处添加@EnableScheduling这个注解。

@SpringBootApplication  
@EnableScheduling  
public class DemoApplication {  
  
    public static void main(String[] args) {  
        SpringApplication.run(DemoApplication.class, args);  
    }  
}  
总开关添加好后,我们只需要对需要定时方法进行配置即可,使用注解@Scheduled。
@Scheduled(cron = "0/2 * * * * *")  //没两秒执行一次
public void timer(){  
    //获取当前时间  
    LocalDateTime localDateTime =LocalDateTime.now();  
    System.out.println("当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));  
}  

@Scheduled(fixedDelay = 5000)  //启动后每隔5秒运行一次
public void timer(){  
    //获取当前时间  
    LocalDateTime localDateTime =LocalDateTime.now();  
    System.out.println("当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));  
}  

@Scheduled(initialDelay = 5000,fixedRate = 6000)  //启动延迟5秒运行一次,后面每隔6秒运行一次
public void timer(){  
    //获取当前时间  
    LocalDateTime localDateTime =LocalDateTime.now();  
    System.out.println("当前时间为:" + localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));  
}  

2.动态定时任务

        由于很多业务场景下我们需要在不重启服务器的情况下对定时任务的时间做出修改,动态定时任务需要连接到数据库,在这里还是默认你已经创建了一个springBoot+mybatis 的项目(如果还不会就,你懂的

https://blog.csdn.net/qq_34996727/article/details/65437616)。

不说啥了,直接贴代码吧。

Mapper:

package com.example.demo.mapper;

import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface TimingTaskMapper {
    String findById(int id);
}

定时任务业务类,这里要注意下,启动的时候执行定时任务还没有进行数据库连接所以访问不到数据库,所以需要先给一个默认执行时间。

package com.example.demo.task;


import com.example.demo.mapper.TimingTaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;
import java.util.Date;

@Configuration
@EnableScheduling
public class CompleteScheduleConfig implements SchedulingConfigurer {

    @Autowired
    private TimingTaskMapper timingTaskMapper;

    private static String cron = "0/5 * * * * ?";
    private static int count = 0;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                // 任务逻辑
                System.out.println("执行定时任务-------------------------"+ LocalDateTime.now());
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                if(count > 0) {
                    cron = timingTaskMapper.findById(1);
                } else {
                    count++;
                }
                // 任务触发,可修改任务的执行周期
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });
    }
}

Mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.TimingTaskMapper">

    <select id="findById" parameterType="java.lang.Integer" resultType="java.lang.String">
        SELECT timing FROM timing_task
        where id = #{id}
    </select>

</mapper>

表数据


以上解决方案基本上可以满足我们一般任务的需求,当然如果还有更复杂的定时业务逻辑还需要更加深入的去学习理解定时任务。




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值