定时任务配置技巧:将表达式配置在业务员代码之外的方法

简介: 该文档介绍了三种不同的方法来定义和管理Java中的定时任务。首先,通过在数据库中创建一个表来存储定时任务的执行周期,并在Spring Boot应用中使用`@Scheduled`注解配合数据库查询来动态执行定时任务。其次,将定时任务的配置移动到Apollo配置中心,利用Apollo的配置能力来控制定时任务的执行。最后,使用Quartz框架并结合Apollo配置文件,动态地管理定时任务的触发间隔和执行时间。此外,还提到了在多机器环境中,可以使用分布式锁来避免任务重复,并推荐了xxl-JOB和elastic-job作为更专业的定时任务解决方案。

 1、 定义在数据库中

1、导入依赖包:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>
    <dependencies>
        <dependency><!--添加Web依赖 -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency><!--添加MySql依赖 -->
             <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency><!--添加Mybatis依赖 配置mybatis的一些初始化的东西-->
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency><!-- 添加mybatis依赖 -->
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

image.gif

2、添加数据库记录:

开启本地数据库mysql,随便打开查询窗口,然后执行脚本内容,如下:

DROP DATABASE IF EXISTS `socks`;
CREATE DATABASE `socks`;
USE `SOCKS`;
DROP TABLE IF EXISTS `cron`;
CREATE TABLE `cron`  (
  `cron_id` varchar(30) NOT NULL PRIMARY KEY,
  `cron` varchar(30) NOT NULL  
);
INSERT INTO `cron` VALUES ('1', '0/5 * * * * ?');

image.gif

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/socks
    username: root
    password: 123456

image.gif

3、创建定时器

数据库准备好数据之后,我们编写定时任务,注意这里添加的是TriggerTask,目的是循环读取我们在数据库设置好的执行周期,以及执行相关定时任务的内容。

具体代码如下:

@Configuration      //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class DynamicScheduleTask implements SchedulingConfigurer {
    @Mapper
    public interface CronMapper {
        @Select("select cron from cron limit 1")
        public String getCron();
    }
    @Autowired      //注入mapper
    @SuppressWarnings("all")
    CronMapper cronMapper;
    /**
     * 执行定时任务.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    String cron = cronMapper.getCron();
                    //2.2 合法性校验.
                    if (StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}

image.gif

2、定义在Apollo中:

package com.Schedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
 * @Description :定时任务配置在Apollo
 * @Author lishuangqiang
 * @Date 2021/1/26
 **/
@Slf4j
@Component
public class DynamicScheduleTaskInApollo {
    /**
     * 其中corntest为配置在Apollo上的corn表达式
     */
    @Scheduled(cron = "${corntest}")
    public void test1() {
        log.info("定时任务开始 :{} ,线程 : {}", LocalDateTime.now().toLocalTime());
    }
    @Value("${timeApollo}")
    private Long timeApollo;
    @PostConstruct
    public void test2() {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                log.info("handleRemindWay2定时任务开始 :{} ,线程 : {}", LocalDateTime.now().toLocalTime(), Thread.currentThread().getName());
                log.info("=========================");
            }
        }, timeApollo, timeApollo, TimeUnit.MILLISECONDS);
    }
}

image.gif

3、用quartz方式 其中定时任务的表达式也可以配置在Apollo

@Configuration
public class QuartzConfig {
 
 
    @Resource
    private ScheduleTask scheduleTask;
 
    /**
     * 配置定时任务1
     * @return
     */
    @Bean(name="firstJobDetail")
    public MethodInvokingJobDetailFactoryBean firstJobDetail(){
        MethodInvokingJobDetailFactoryBean method = new MethodInvokingJobDetailFactoryBean();
        // 为需要执行的实体类对应的对象
        method.setTargetObject(scheduleTask);
        // 需要执行的方法
        method.setTargetMethod("test");
        // 是否并发执行
        method.setConcurrent(false);
        return method;
    }
 
 
    /**
     *   配置触发器1
     *   @param firstJobDetail
     *   @return
     */
    @Bean(name="firstTrigger")
    public SimpleTriggerFactoryBean firstTrigger(JobDetail firstJobDetail){
        SimpleTriggerFactoryBean simpleBean = new SimpleTriggerFactoryBean();
        simpleBean.setJobDetail(firstJobDetail);
        // 设置任务启动延迟
        simpleBean.setStartDelay(1000);
        // 每1秒执行一次
        simpleBean.setRepeatInterval(1000);
        //设置重复计数
        //simpleBean.setRepeatCount(0);
        return simpleBean;
    }
 
    /**
     *  配置Scheduler
     */
    @Bean(name = "scheduler")
    public SchedulerFactoryBean schedulerFactoryBean(Trigger firstTrigger){
        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
        factoryBean.setTriggers(firstTrigger);
        return factoryBean;
    }
 
 
 
}

image.gif

@Component
public class ScheduleTask {
 
   public void test() {
       System.out.println("====================================");
   }
 
}

image.gif

4、把参数配置到.properties文件中

package com.accord.task;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
@Component
public class ScheduledTask {
 
  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
 
  //@Scheduled(fixedDelayString = "${jobs.fixedDelay}")
  @Scheduled(fixedDelayString = "2000")
  public void getTask1() {
    System.out.println("任务1,从配置文件加载任务信息,当前时间:" + dateFormat.format(new Date()));
  }
 
  @Scheduled(cron = "${jobs.cron}")
  public void getTask2() {
    System.out.println("任务2,从配置文件加载任务信息,当前时间:" + dateFormat.format(new Date()));
  }
}

image.gif

application.properties文件:

jobs.fixedDelay=5000
jobs.cron=0/5 * *  * * ?

image.gif

上面的方式在做定时任务 时有多个机器最好用redission做分布式锁方式防止重复调用,当然这样的情况最好用业界的xxl-JOB或者elastic-job,最好,支持分片配置

借鉴:https://www.cnblogs.com/mmzs/p/10161936.html

和java定时任务实现的4种方式_scheduledthreadpool.scheduleatfixedrate(timertask,-CSDN博客,还要自己的之前的东西

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
存储 Kubernetes 应用服务中间件
【K8S系列】深入解析无状态服务
【K8S系列】深入解析无状态服务
1221 2
|
开发工具 git
Git - Smart Checkout、Force Checkout 区别
Git - Smart Checkout、Force Checkout 区别
3297 0
Git - Smart Checkout、Force Checkout 区别
|
4月前
|
人工智能 运维 自然语言处理
强制国标18个月倒计时:企业AI安全的六大关口怎么过
6月27日,国标委发布《智能体应用安全基本要求》强制性国标(2026年41号),设六道安全关:资产盘点、身份权限、数据管控、多模态防护、全链路审计、应急熔断。本文不复述条文,而是逐关解析落地难点与工程解法——从流量侧自动盘点AI资产,到Agent身份映射、PII实时拦截、多模态越狱防御、结构化审计溯源,再到凭证级秒级熔断,助力企业高效合规。
454 0
|
5月前
|
人工智能 自然语言处理 小程序
怎么开发自己的小程序?2026 三种主流方式实测对比
2026年,AI全栈开发平台让“零代码做可上线微信小程序”成为现实:自然语言描述需求→AI自动生成完整代码→1小时内提审。成本低至几十元/月,无需编程,3步完成从想法到上线。
1726 0
|
5月前
|
人工智能 监控 安全
AI 智能体开发与上线
本文系统阐述AI智能体(Agent)从0到1的全生命周期工程实践:涵盖架构设计、提示工程、工具集成、多Agent编排;强化安全护栏与幻觉控制;支持API服务化、容器化部署及多端接入;通过全链路监控与数据飞轮实现持续优化。
|
8月前
|
供应链 安全 Java
Java安全漏洞深潜——反序列化、Log4Shell与供应链攻击
由于Java广泛应用于银行、政府、大型企业,其安全性备受瞩目。然而近年来频频爆发的高危漏洞(Log4Shell、Spring4Shell、FastJSON反序列化等)敲响了警钟。
829 7
|
5月前
|
关系型数据库 MySQL 分布式数据库
阿里云云原生数据库PolarDB对接使用完全指南:从集群创建到应用集成
本文提供了一份完整的阿里云云原生数据库PolarDB对接使用指南。首先介绍PolarDB的云原生架构(计算存储分离、一写多读)及其核心优势。接着详细讲解控制台创建集群的完整流程,包括计费模式选择、网络与可用区规划、白名单与数据库账号配置。深入解析三种连接地址(主地址、集群地址、自定义地址)的区别与适用场景,并通过JDBC、Python、Spring Boot等多种代码示例演示应用程序如何对接PolarDB。针对数据迁移场景,重点介绍DTS全量+增量迁移方案及零停机迁移最佳实践。在性能优化方面,涵盖数据库代理读写分离配置、事务级连接池、参数调优与慢查询分析。最后阐述云监控告警配置与日常运维要点,
|
8月前
|
Kubernetes Cloud Native 微服务
【微服务与云原生架构】 云原生核心:Docker、K8s架构、核心资源(Pod/Deployment/Service/Ingress)、Pod生命周期、健康检查、滚动更新、自动扩缩容HPA
本文系统梳理微服务与云原生架构的知识体系:以Docker实现环境一致与轻量交付,K8s提供容器编排底座;涵盖Pod、Deployment、Service、Ingress四大核心资源,以及健康检查、滚动更新、HPA自动扩缩容等关键能力,构建高可用、可弹性、可观测的现代分布式应用架构闭环。
|
人工智能 运维 Java
SpringBoot+MySQL实现动态定时任务
这是一个基于Spring Boot的动态定时任务Demo,利用spring-context模块实现任务调度功能。服务启动时会扫描数据库中的任务表,将任务添加到调度器中,并通过固定频率运行的ScheduleUpdater任务动态更新任务状态和Cron表达式。核心功能包括任务的新增、删除与Cron调整,支持通过ScheduledFuture对象控制任务执行。项目依赖Spring Boot 2.2.10.RELEASE,使用MySQL存储任务信息,包含任务基类ITask及具体实现(如FooTask),便于用户扩展运维界面以增强灵活性。
567 10
|
Docker 容器
如何解决Docker容器和宿主机时间同步问题
在使用了Docker以后,大家可能遇到的一个问题就是Docker容器的时间和宿主机时间不同步。造成这个问题的主要原因是宿主机设置了时区,而Docker容器并且设置,导致两者相差8小时。 接下来,我们通过在在宿主机和容器里分别执行date命令来看下实际的情况。 在宿主机执行date命令的结果:
35011 0