首页 > 其他分享 >springboot 创建动态定时任务

springboot 创建动态定时任务

时间:2023-06-16 16:05:06浏览次数:32  
标签:springboot jiaotongbu 创建 springframework api import org 定时 com


 

首先需要在application 中配置注解 @EnableScheduling开启定时器 


初始化定时任务周期 就是去数据库查询初始配置的定时任务,如果执行过程中有结果或者没有结果都可以对数据库表进行修改,然后下次再按修改后的时间执行任务

 附上数据库表结构

springboot 创建动态定时任务_json

springboot 创建动态定时任务_spring_02

package com.jiaotongbu.api.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiaotongbu.api.controller.BaseController;
import com.jiaotongbu.api.entity.ApiCorn;
import com.jiaotongbu.api.entity.ApiHalfYearReport;
import com.jiaotongbu.api.service.ApiCornService;
import com.jiaotongbu.api.service.ApiHalfYearReportService;
import com.jiaotongbu.api.util.RestfulUtilNew;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
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.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
@Component
@Configuration      //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class HalfYearTask extends BaseController implements SchedulingConfigurer {
    private static Logger logger = Logger.getLogger(HalfYearTask.class);
    private static final String corn="0 0 0 1 1,7 ? ";
    @Autowired
    private ApiHalfYearReportService apiHalfYearReportService;
    @Autowired
    private ApiCornService apiCornService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
            scheduledTaskRegistrar.addTriggerTask(() ->{
                try {
                    LocalDateTime time=LocalDateTime.now();
                    DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    String strDate2 = dtf2.format(time);
                    logger.info("开始执行半年报..."+strDate2);
                    Map<String, String> map = new HashMap<>();
                    LocalDateTime now = LocalDateTime.now();
                    // 1月1号往前推6个月 然后获取那个时间的年
                    LocalDateTime localDateTime1 = now.minusMonths(6);
                    String type="00";  //00:代表上半年;01代表下半年
                    if (7<=localDateTime1.getMonthValue()){
                        type="01";
                    }
                    map.put("year",String.valueOf(localDateTime1.getYear()));
                    map.put("type",type);
                    map.put("identity",identity);
                    String jsonMap = JSONArray.toJSONString(map);
                    String resultStr = RestfulUtilNew.sendMd5JsonPost(halfYearReportUrl, jsonMap);
                    JSONObject jsonObject = JSONArray.parseObject(resultStr);
                    String code = jsonObject.getString("code");
                    String data = jsonObject.getString("data");
                    JSONArray objects = JSONArray.parseArray(data);
                    ApiCorn apiCorn = apiCornService.queryById(1);
                    // 如果data中没有值 在次日继续访问, 如果有值 则设置为 半年取一次。
                    if (objects.size()<=0){
                        LocalDateTime localDateTime = now.plusDays(1);
                        int dayOfMonth = localDateTime.getDayOfMonth();
                        int monthValue = localDateTime.getMonthValue();
                        String cornvalue = "0 0 0 "+dayOfMonth+" "+monthValue+" ?";
                        apiCorn.setCorn(cornvalue);
                    }else{
                        if(!corn.equals(apiCorn.getCorn())){
                            apiCorn.setCorn(corn);
                        }
                    }
                    apiCornService.update(apiCorn);
                    logger.info("半年报共返回"+objects.size()+"条数据");
                    if (ApiResultStatusEnum.SUCCESS.value() == (Integer.parseInt(code))){
                        logger.info(ApiResultStatusEnum.SUCCESS.name());
                        for (int i = 0; i < objects.size(); i++) {
                            String jsonString = objects.getJSONObject(i).toJSONString();
                            logger.info("第"+i+1+"条数据:"+jsonString);
                            ApiHalfYearReport apiHalfYearReport = JSONArray.parseObject(jsonString, ApiHalfYearReport.class);
                            apiHalfYearReportService.insert(apiHalfYearReport);
                        }
                        logger.info("半年报执行完毕...");
                    }else{
                         ApiResultStatusEnum error = ApiResultStatusEnum.getByValue(Integer.parseInt(code));
                        logger.error("半年报执行失败:"+error.getName());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error("半年报执行失败:"+e.getMessage());
                }
            },triggerContext -> {
                // 初始化定时任务周期
                ApiCorn apiCorn = apiCornService.queryById(1);
                CronTrigger trigger = new CronTrigger(apiCorn.getCorn());
                return trigger.nextExecutionTime(triggerContext);
            });
    }
}

springboot 创建动态定时任务_spring_03

标签:springboot,jiaotongbu,创建,springframework,api,import,org,定时,com
From: https://blog.51cto.com/u_16163393/6500185

相关文章

  • SpringBoot动态导出word文档POI-TL
    1、引入依赖,同步使用hutool工具进行开发<dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.10.0</version></dependency><dependency&......
  • SpringBoot 接口返回响应体修改
    在开发中,有时候会遇到一些统一修改http接口响应体内容的场景,比如返回体Wrapper统一增加一些数据包装处理。解决思路:通过自定义注解+切面 或者自定义注解+ ResponseBodyAdvice处理接口返回体1、创建自定义注解 importjava.lang.annotation.ElementType;importjava......
  • springboot-Quartz定时任务并持久化
    新建项目,添加依赖新建一个springboot项目,勾选下springboot,以及quartz依赖 或者我们可以直接在pom.xml文件中直接添加依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-quartz</artifactId>......
  • JwtToken---Token上下文,负责token的创建和验证
    publicclassJwtToken{///<summary>///秘钥,可以从配置文件中获取///</summary>publicstaticstringsecurityKey="GQDstclechenxxxxxxxxojPOXOYg5MbeJ1XT0uxxxxxxvVBrk";///<summary>///创建jw......
  • springboot防重复提交
    springboot防重复提交1、场景网页卡顿的时候,用户点击会造成重复操作如果前端不做防重复操作。会导致重复提交,重复下单等意外操作。而且对于系统资源来说也是一种浪费常规的解决方法是让前端把点击后的按钮设置为不可点击,这样基本上能就能解决了。99.999999%能解决。前端这么弄......
  • /*创建消息队列*/ msgid=msgget(IPC_PRIVATE,0666 | IPC_CREAT);
    #include<stdlib.h>#include<stdio.h>#include<string.h>#include<errno.h>#include<unistd.h>#include<sys/types.h>#include<sys/ipc.h>#include<sys/msg.h>#defineMAX_TEXT512structmy_msg_st{......
  • springboot整合cache缓存
    第一步:在pom.xml文件中导入对应坐标<!--cache--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency>第二步:启用缓存在启动......
  • springboot 解决跨域问题
    什么是跨域指从一个域名网页去请求另一域名页面的资源,比如baidu.com请求google.com中的资源,但是这种情况是不允许的,因为由浏览器的同源策略,使浏览器对js增加安全限制,即就是阻止不同域下的js进行交互。判断域是否相同是通过判断协议、域名、端口中有任何一个不同,则为不同的域......
  • springboot整合redis
    1、添加依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>2、配置redis通过spring.redis.xxx来配置redis的信息spring.redis.hos......
  • springboot整合持久层
    springboot整合持久层1、整合mybatis这里以多数据源为例第一步创建springboot时,选上mybatis依赖在添加数据库驱动依赖:<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.23<......