java定时任务传参和不传参

不传参数

页面配置

java 复制代码
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fastbee.common.core.domain.entity.SysDictData;
import com.fastbee.system.mapper.SysDictDataMapper;
import com.ktg.mes.pur.purchase.domain.PurExchangeRate;
import com.ktg.mes.rate.service.IPurExchangeRateService;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("TimedExecution")
public class TimedExecution {

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private IPurExchangeRateService purExchangeRateService;

    /**
     * 每天九点半定时查询汇率并更新数据库
     */
    public void getAutomaticAcquisitionRate() {
        PurExchangeRate purExchangeRate = new PurExchangeRate();
        List<SysDictData> currencyType = sysDictDataMapper.selectDictDataByType("currency_type");
        //轮询
        for (SysDictData sysDictData : currencyType) {
            String dictValue = sysDictData.getDictValue();
            if ("USD".equals(sysDictData.getDictValue())) {
                purExchangeRate.setAmericanDollar(new BigDecimal(send(dictValue)));  //美元
            } else if ("EUR".equals(sysDictData.getDictValue())) {
                purExchangeRate.setEuro(new BigDecimal(send(dictValue))); //欧元
            } else if ("GBP".equals(sysDictData.getDictValue())) {
                purExchangeRate.setPoundSterling(new BigDecimal(send(dictValue)));//英镑
            } else if ("HKD".equals(sysDictData.getDictValue())) {//港币
                purExchangeRate.setHongKongDollar(new BigDecimal(send(dictValue)));
            } else if ("JPY".equals(sysDictData.getDictValue())) {
                purExchangeRate.setYen(new BigDecimal(send(dictValue)));
            }
        }

        //插入表
        purExchangeRate.setAutomaticAcquisitionRate("1");
        purExchangeRate.setRmb(new BigDecimal(1));
        purExchangeRate.setCreateTime(new Date());
        purExchangeRateService.insertPurExchangeRate(purExchangeRate);

    }

//    public static void main(String[] args) {
//        //测试
//        send("USD");
//    }

    public static String send(String toCurrency) {
        String rate = "";

        String host = "https://jisuhuilv.market.alicloudapi.com";
        String path = "/exchange/convert";
        String method = "GET";
        String appcode = "d668a290143d4f7d90c61bd54e4de7b5";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求,定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("amount", "1");
        querys.put("from", toCurrency);
        querys.put("to", "CNY");
        try {
            HttpResponse response = HttpUtil.doGet(host, path, method, headers, querys);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                //执行成功
                String body = EntityUtils.toString(response.getEntity());
                //解析数据
                JSONObject jsonObject = JSON.parseObject(body);
                JSONObject result = jsonObject.getJSONObject("result");
                rate = result.getString("rate");
                return rate;
            }
            //                System.out.println("币种:"+result.getString("fromname"));
//                System.out.println("汇率:"+result.getString("rate"));
//                System.out.println("数据集合是:"+body);

            return null;
//            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


}

传参

参数

第一个参数是shell脚本的位置和名字,第二个是等这个脚本启动几分钟,第三个是否打印shell脚本的输出

主要代码

java 复制代码
package com.boc.quartz.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

@Component("scriptTask")
@Slf4j
public class ScriptTask {
	
	/**
     * 
     * @param shell_path shell脚本的位置和名字 当前路径下的脚本 './test.sh'
     * @param wait_minutes 等几分钟
     * @param printShellOut 是否打印脚本日志 N/Y
     */
	public void callShell(String shell_path, Integer wait_minutes , String printShellOut) {
		// 获取shell返回流
        BufferedInputStream in = null;
        // 字符流转换字节流
        BufferedReader br = null;
        
        if(printShellOut==null) printShellOut="N";
        
        try{
            //shell执行状态
            // 定义传入shell脚本的参数,将参数放入字符串数组里
            String cmds[] = new String[1];
            cmds[0] = shell_path;
            // 执行shell脚本
            log.debug("Execute Shell : "+shell_path);
            Process pcs = Runtime.getRuntime().exec(cmds);
            try {
                log.debug("Execute Shell ["+shell_path+"]  wait "+wait_minutes+" MINUTES");
                pcs.waitFor(wait_minutes, TimeUnit.MINUTES);
            } catch (InterruptedException e) {
                log.error("Execute Shell ["+shell_path+"] has Exception", e.getMessage());
            }
            log.debug("Execute ShellTask ["+shell_path+"] finished.");
            
            if(printShellOut.toUpperCase().equals("Y")) {
            	log.debug("Execute ShellTask ["+shell_path+"] result print start.");
            	in = new BufferedInputStream(pcs.getInputStream());
                // 字符流转换字节流
                br = new BufferedReader(new InputStreamReader(in));
                String line = null;
                while ((line = br.readLine()) != null) {
                    log.debug("ExecuteShellTask result:",line);
                }
                log.debug("Execute ShellTask ["+shell_path+"] result print end.");
            }
            
        }catch (Exception ex){
            log.error("ShellTask Exception", ex.getMessage());
        }finally {
            // 关闭输入流
        	try {
        		if(printShellOut.toUpperCase().equals("Y")) {
	        		br.close();
	                in.close();
        		}
        	}catch(Exception e) {
        		log.error("ShellTask Exception", e.getMessage());
        	}
            
        }
	}

}
复制代码
相关推荐
喵手1 小时前
玩转Java网络编程:基于Socket的服务器和客户端开发!
java·服务器·网络
再见晴天*_*2 小时前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
lqjun08274 小时前
Qt程序单独运行报错问题
开发语言·qt
hdsoft_huge5 小时前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
风中的微尘6 小时前
39.网络流入门
开发语言·网络·c++·算法
雨白6 小时前
Java 多线程指南:从基础用法到线程安全
android·java
Hungry_Shark6 小时前
IDEA版本控制管理之使用Gitee
java·gitee·intellij-idea
赛姐在努力.6 小时前
《IDEA 突然“三无”?三秒找回消失的绿色启动键、主菜单和项目树!》
java·intellij-idea
未来之窗软件服务6 小时前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
猎板PCB黄浩6 小时前
从废料到碳减排:猎板 PCB 埋容埋阻的绿色制造革命,如何实现环保与性能双赢
java·服务器·制造