欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringTask实现定时任务

程序员文章站 2022-05-24 20:51:09
...

SpringTask实现定时任务

  1. 配置文件
    beans中添加
xmlns:task="http://www.springframework.org/schema/task"

http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd

开启注解扫描包

<!-- task任务注解扫描包(定时器开关) -->
	<task:annotation-driven/>

指定扫描包的位置

<!-- 扫描位置是 -->
<context:annotation-config/>
	<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:component-scan base-package="com.risen.wechat.task"/>
  1. 只需要在代码中注解使用定时时间即可
package com.risen.wechat.task.impl;

import com.risen.core.dao.ICoreOrganizationDao;
import com.risen.core.model.CoreOrganization;
import com.risen.core.service.ICoreOrganizationService;
import com.risen.hp.fastjson.JSON;
import com.risen.hp.fastjson.JSONArray;
import com.risen.hp.fastjson.JSONObject;
import com.risen.wechat.task.Task;
import com.risen.wechat.unit.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * @author hew
 * @date 2019/10/18 11:57
 */
@Component
public class TaskImpl implements Task {

    @Autowired
    public ICoreOrganizationDao coreOrganizationDao;
    @Autowired
    private ICoreOrganizationService coreOrganizationService;

    @Override
//    @Scheduled(cron = "0/20 * * * * ?")
    public void taskTimer() {
        CoreOrganization coreOrganization = new CoreOrganization();
        //发送http请求获取到json数据(拿到智慧平台传递过来的数据)
        String url = "";
        JSONObject jsonObject = HttpUtil.sendGetJson(url, "");
        String data = jsonObject.getString("data");
        //转换成json数组
        JSONArray objects = JSON.parseArray(data);
        System.out.println(objects);
        //定义map集合(将需要插入的json数据全部获取)
        Map<String, Map<String, String>> map = new HashMap<>();
        //定义一个list集合
        List<String> list1 = new ArrayList<>();
        //遍历json数组
        if (objects.size() > 0) {
            for (int i = 0; i < objects.size(); i++) {
                JSONObject job = objects.getJSONObject(i);
                //CRORG_UNID  unid自动生成
                //CRORG_UUID 部门uuid
                String crorgUuid = null;
                try {
                    crorgUuid = job.get("crorgUuid").toString();
                }catch (Exception e){
                    crorgUuid = "";
                }
                //CRORG_LEVEL_CODE 层级编码
                String crorgLevelCode = null;
                try {
                    crorgLevelCode = job.get("crorgLevelCode").toString();
                }catch (Exception e){
                    crorgLevelCode = "";
                }
                //CRORG_NUMBER 机构编号
                String crorgNumber = null;
                try {
                    crorgNumber = job.get("crorgNum").toString();
                }catch (Exception e){
                    crorgNumber = "";
                }
                //CRORG_PARENT_UUID 父节点PID
                String crorgParentUuid = null;
                try {
                    crorgParentUuid = job.get("crorgParentUuid").toString();
                }catch (Exception e){
                    crorgParentUuid = "";
                }
                //CRORG_NAME 机构名称
                String crorgName = null;
                try {
                    crorgName = job.get("crorgShortName").toString();
                }catch (Exception e){
                    crorgName = "";
                }
                //CRORG_FULL_NAME 机构全称
                String crorgFullName = null;
                try {
                    crorgFullName = job.get("crorgFullName").toString();
                }catch (Exception e){
                    crorgFullName = "";
                }
                //CRORG_ADDRESS 机构地址
                String crorgAddress = null;
                try {
                    crorgAddress = job.get("crorgAddress").toString();
                }catch (Exception e){
                    crorgAddress = "";
                }
                //CRORG_PHONE 机构电话
                String crorgPhone = null;
                try {
                    crorgPhone = job.get("crorgPhone").toString();
                }catch (Exception e){
                    crorgPhone = "";
                }
                //CRORG_TYPE 组织类型
                String crorgType = null;
                try {
                    crorgType = job.get("crorgType").toString();
                }catch (Exception e){
                    crorgType = "";
                }
                //CRORG_STATUS 状态
                String crorgStatus = null;
                try {
                    crorgStatus = job.get("crorgStatus").toString();
                }catch (Exception e){
                    crorgStatus = "";
                }
                //CRORG_ORDER 排序号
                Integer crorgOrder = null;
                try {
                    crorgOrder = Integer.parseInt(job.get("crorgOrd").toString());
                }catch (Exception e){
                    crorgOrder = -1;
                }

                //CRORG_CREATE_TIME 创建日期
//                String crorgCreateTime = job.get("crorgCdate").toString();
                //CRORG_UPDATE_TIME 修改日期
//                String crorgUpdateTime = job.get("lastUpdateTime").toString();
                //CRORG_CREATOR 创建者
                //CRORG_PINYIN 拼音
                //CRORG_OUTER_UUID 外部标识
                //CRORG_NKC 九键代码
                //CRORG_GRP_OWNERS 所属组群

                List<CoreOrganization> list2 = coreOrganizationDao.findByIdList(Arrays.asList(crorgUuid));
                //如果没有查询到数据,则进行插入操作
                coreOrganization.setCrorgUuid(crorgUuid);
                coreOrganization.setCrorgLevelCode(crorgLevelCode);
                coreOrganization.setCrorgNumber(crorgNumber);
                coreOrganization.setCrorgParentUuid(crorgParentUuid);
                coreOrganization.setCrorgName(crorgName);
                coreOrganization.setCrorgFullName(crorgFullName);
                coreOrganization.setCrorgAddress(crorgAddress);
                coreOrganization.setCrorgPhone(crorgPhone);
                coreOrganization.setCrorgType(crorgType);
                coreOrganization.setCrorgStatus(crorgStatus);
                coreOrganization.setCrorgOrder(crorgOrder);
                if (list2.size() == 0) {
                    //直接调用save方法
                    save(coreOrganization);
                } else {
                    update(coreOrganization);
                }
            }
        }
    }

    public void save(CoreOrganization coreOrganization) {
        PreparedStatement ps = null;
        Connection conn = null;
        ResultSet rs = null;

        //编写sql
        String sql = "INSERT INTO core_organization(CRORG_UUID,CRORG_LEVEL_CODE,CRORG_NUMBER,CRORG_PARENT_UUID" +
                ",CRORG_NAME,CRORG_FULL_NAME,CRORG_ADDRESS,CRORG_PHONE,CRORG_TYPE,CRORG_STATUS,CRORG_ORDER) values(?,?,?,?,?,?,?,?,?,?,?) ";

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://60.191.64.2:9421/risen_badj?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull",
                    "root", "root");
//            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);

            ps.setString(1, coreOrganization.getCrorgUuid());
            ps.setString(2, coreOrganization.getCrorgLevelCode());
            ps.setString(3, coreOrganization.getCrorgNumber());
            ps.setString(4, coreOrganization.getCrorgParentUuid());
            ps.setString(5, coreOrganization.getCrorgName());
            ps.setString(6, coreOrganization.getCrorgFullName());
            ps.setString(7, coreOrganization.getCrorgAddress());
            ps.setString(8, coreOrganization.getCrorgPhone());
            ps.setString(9, coreOrganization.getCrorgType());
            ps.setString(10, coreOrganization.getCrorgStatus());
            ps.setInt(11, coreOrganization.getCrorgOrder());

            ps.executeUpdate();            //执行sql语句

            System.out.println("插入成功(* ̄︶ ̄)");
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
//                rs.close();
                ps.close();
                conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

    }

    public void update(CoreOrganization coreOrganization) {

        PreparedStatement ps = null;
        Connection conn = null;
        ResultSet rs = null;

        //编写sql
        String sql = "UPDATE core_organization SET " +
                "CRORG_LEVEL_CODE = ?, " +
                "CRORG_NUMBER = ?, " +
                "CRORG_PARENT_UUID = ?, " +
                "CRORG_NAME = ?, " +
                "CRORG_FULL_NAME = ?, " +
                "CRORG_ADDRESS = ?, " +
                "CRORG_PHONE = ?, " +
                "CRORG_TYPE = ?, " +
                "CRORG_STATUS = ?, " +
                "CRORG_ORDER = ?, " +
                "CRORG_UPDATE_TIME = ? " +
                "WHERE CRORG_UUID = ?";

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://60.191.64.2:9421/risen_badj?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull",
                    "root", "root");
//            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);

            ps.setString(1, coreOrganization.getCrorgLevelCode());
            ps.setString(2, coreOrganization.getCrorgNumber());
            ps.setString(3, coreOrganization.getCrorgParentUuid());
            ps.setString(4, coreOrganization.getCrorgName());
            ps.setString(5, coreOrganization.getCrorgFullName());
            ps.setString(6, coreOrganization.getCrorgAddress());
            ps.setString(7, coreOrganization.getCrorgPhone());
            ps.setString(8, coreOrganization.getCrorgType());
            ps.setString(9, coreOrganization.getCrorgStatus());
            ps.setInt(10, coreOrganization.getCrorgOrder());
            /*try {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                String format = df.format(new Date());
                Date date = df.parse(format);
            } catch (ParseException e) {
                e.printStackTrace();
            }*/
//            java.util.Date d = new java.util.Date();
            Date d = new Date();
            Timestamp timestamp = new Timestamp(d.getTime());
            ps.setTimestamp(11, timestamp);
            ps.setString(12, coreOrganization.getCrorgUuid());

            ps.executeUpdate();            //执行sql语句

            System.out.println("更新成功(* ̄︶ ̄)");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
}




  1. 具体时间使用@Scheduled注解表示详细定时时间。