精华内容
参与话题
问答
  • 入门学习Linux常用必会60个命令实例详解doc/txt

    千次下载 热门讨论 2011-06-09 00:08:45
    文件为doc版,可自行转成txt,在手机上看挺好的。 本资源来自网络,如有纰漏还请告知,如觉得还不错,请留言告知后来人,谢谢!!!!! ...入门学习Linux常用必会60个命令实例详解 ...Linux提供了大量的命令,利用它...
  • Linux命令笔记

    2019-03-14 09:16:58
    系统管理/系统定时任务 1:crond服务管理与访问控制 语法:crontab [选项] 系统管理/系统资源查看 1:vmstat命令监控系统资源 语法: vmstat 刷新延时 刷新次数 2:dmesg开机时内核检测信息 语法: dmesg 3:free查看...
  • 根据网上的解决方法,我已经关闭了定时任务Scheduler,关闭了开启定时任务的线程池,也关闭了数据源。为什么还是报错? 我的代码 package com.yz.robot.spring; import ...
  • maven jar project项目一个 ...project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4....

     

    maven jar project项目一个

    pom文件:

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.test</groupId>
      <artifactId>test-jar-quartz</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      
      
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.quartz-scheduler</groupId>
                <artifactId>quartz</artifactId>
                <version>2.2.3</version>
            </dependency>
        </dependencies>
    
    </project>

     

    java代码:

    package com.test1;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.quartz.DisallowConcurrentExecution;
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    
    @DisallowConcurrentExecution//此注解目的为一定是已经执行完一个任务才按照时间去开启下一个任务
    public class MyJob implements Job {
     
        public void execute(JobExecutionContext context) throws JobExecutionException {
            //打印当前的执行时间,格式为yyyy-MM-dd HH:mm:ss
            // 编写具体的业务逻辑。
            Date date=new Date();
            SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//规范格式
            System.out.println("当前时间为:"+sf.format(date));
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Hello World!---线程名---: "+Thread.currentThread().getName()+"--当前对象--:"+this);
        }
     
    }

     

    package com.test1;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.quartz.JobBuilder;
    import org.quartz.JobDetail;
    import org.quartz.Scheduler;
    import org.quartz.SchedulerException;
    import org.quartz.SchedulerFactory;
    import org.quartz.SimpleScheduleBuilder;
    import org.quartz.Trigger;
    import org.quartz.TriggerBuilder;
    import org.quartz.impl.StdSchedulerFactory;
     
    public class MyScheduler {
        public static void main(String[] args) throws SchedulerException
        {
            //创建一个JobDetail实例,将该实例与MyJob Class绑定。
            JobDetail jobDetail=JobBuilder.newJob(MyJob.class).withIdentity("myJob", "group1").build();
            //创建一个Trigger实例,定义该Job立即执行,并且每隔3秒钟重复一次,
            Trigger trigger=TriggerBuilder
                    .newTrigger()
                    .withIdentity("myTrigger","group1")
                    .startNow()
                    .withSchedule(SimpleScheduleBuilder
                            .simpleSchedule()
                            .withIntervalInSeconds(3)
                            .repeatForever())
                    .build();
            SchedulerFactory sf=new StdSchedulerFactory();
            Scheduler scheduler=sf.getScheduler();
            scheduler.start();
            Date date=new Date();
            SimpleDateFormat sfd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//规范格式
            //System.out.println("当前时间为:"+sfd.format(date));
            scheduler.scheduleJob(jobDetail, trigger);
        }
    }

     

    转载于:https://www.cnblogs.com/libin6505/p/10571623.html

    展开全文
  • import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTas...
    
     
    这是管理类:
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    
    /**
     * Created by Administrator on 2017/9/29.
     */
    public class TaskManager {
        /**
         * 开启任务
         */
        //默认时间间隔一天
        private static long PERIOD_TIME = 24 * 60 * 60 * 1000;
        Log log = LogFactory.getLog(TaskManager.class);
    
        public void startTask(TimerTask task, int dayInterval, int hour, int minute){
            PERIOD_TIME =  dayInterval * 24 * 60 * 60 * 1000;
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, hour);
            calendar.set(Calendar.MINUTE, minute);
            calendar.set(Calendar.SECOND, 0);
            //执行定时任务的时间
            Date date=calendar.getTime();
            //为了避免若容器启动的时间晚于定时时间,在重启容器的时候会立刻执行该任务
            if (date.before(new Date())) {
                date = this.addDay(date, 1);
            }
            Timer timer = new Timer();
            //任务在指定的时间开始进行重复的固定延迟执行
            timer.schedule(task,date);
    
          
        }
        // 增加或减少天数
        public Date addDay(Date date, int num) {
            Calendar startDT = Calendar.getInstance();
            startDT.setTime(date);
            startDT.add(Calendar.DAY_OF_MONTH, num);
            return startDT.getTime();
        }
    }
    
    
     
    这是监听:
    
     
    import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener;  /**  * Created by Administrator on 2017/9/29.  */ public class RankTaskListener implements ServletContextListener { @Override  public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("开启监听了.2点28准时启动...........");  String day="1";  String hour="14";  String minute="28";  new TaskManager().startTask(new RankTask(),  Integer.parseInt(day), Integer.parseInt(hour), Integer.parseInt(minute));  } @Override  public void contextDestroyed(ServletContextEvent servletContextEvent) { } } 

     

    这是定时任务:

     

    
     
    import java.util.TimerTask;  /**  * Created by Administrator on 2017/9/29.  */ public class RankTask extends TimerTask { @Override  public void run() { System.out.println("...............任务执行了.............");  } }

     

    web .xml配置监听:

     

    
     
    <listener>  <listener-class>com.mytest.task.RankTaskListener</listener-class> </listener>

     

    展开全文
  • -- 第三步:开启定时任务 --> ``` 2.QuartzTaskAction.action内容 ``` package com.test.action; public class QuartzTaskAction{ public void xhhfDates(){ System.out....
  • 这次在SpringBoot项目中使用Schedule注解实现定时任务 需求:每月初下载http://www.safe.gov.cn/safe/gzhbdmyzslb/index.html中上个月的表格进行解析。 导入依赖 <dependencies> <!-- ...

    这次在SpringBoot项目中使用Schedule注解实现定时任务

    需求:每月初下载http://www.safe.gov.cn/safe/gzhbdmyzslb/index.html中上个月的表格进行解析。

    导入依赖

    <dependencies>
    		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    		<dependency>
    			<groupId>org.apache.httpcomponents</groupId>
    			<artifactId>httpclient</artifactId>
    			<version>4.5.5</version>
    		</dependency>
    		<dependency>
    			<groupId>commons-io</groupId>
    			<artifactId>commons-io</artifactId>
    			<version>2.5</version>
    		</dependency>
    		<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
    		<dependency>
    			<groupId>org.jsoup</groupId>
    			<artifactId>jsoup</artifactId>
    			<version>1.11.3</version>
    		</dependency>
    		<dependency>
    			<groupId>org.jsoup</groupId>
    			<artifactId>jsoup</artifactId>
    			<version>1.11.3</version>
    		</dependency>
    		<dependency>
    			<groupId>org.seleniumhq.selenium</groupId>
    			<artifactId>selenium-java</artifactId>
    			<version>3.3.1</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi</artifactId>
    			<version>3.17</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-ooxml</artifactId>
    			<version>3.17</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-examples</artifactId>
    			<version>3.17</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-excelant</artifactId>
    			<version>3.17</version>
    		</dependency>
    		<dependency>
    			<groupId>com.alibaba</groupId>
    			<artifactId>fastjson</artifactId>
    			<version>1.2.46</version>
    		</dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-autoconfigure</artifactId>
                <version>2.1.5.RELEASE</version>
            </dependency>
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-context</artifactId>
    			<version>5.1.7.RELEASE</version>
    		</dependency>
    	</dependencies>
    

    解决思路

    在这里插入图片描述
    列表类型,每月初获取第一条中的超链接,打开下载页面
    在这里插入图片描述

                    //根据唯一标识获得className为"list_conr"的标签
                    Elements listConr = document.getElementsByClass("list_conr");
    
                    //主页按照不同月份有不同链接,是一个列表,我们需要获得最新的月份,即第一个列表里的链接,该链接能打开表格下载的网页
                    Element ahref=listConr.select("ul").get(0).select("li").get(0).selectFirst("dt").selectFirst("a");
                    String hrefDetail=ahref.attr("href");
    

    在这里插入图片描述
    在新的页面要用同样的方法获得xlsx的下载地址

                            //获得xlsx的下载链接url
                            Element axlsxhref=document1.getElementsByClass("detail_content").first().select("div").first().select("p").get(2).select("a").first();
                            String axlsxhrefDetail=axlsxhref.attr("href");
    

    下载表格,加了定时任务为了区分,在表格文件名上包括当前的时间

                                    SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日HH_mm_ss");
                                    String date=dateFormat.format(new Date());
    
                                    //文件复制
                                    InputStream inputStream = entity3.getContent();
                                    FileUtils.copyToFile(inputStream,new File("E:\\rmbrate\\rate"+date+fileType));
    
    

    处理表格数据

    在这里插入图片描述
    根据表格内容设计POJO

    public class ConversionRateToDollar {
        private String month;
        private String currency;
        private String currencyCN;
        private String unit;
        private double rate;
    
        public String getMonth() {
            return month;
        }
    
        public void setMonth(String month) {
            this.month = month;
        }
    
        public String getCurrency() {
            return currency;
        }
    
        public void setCurrency(String currency) {
            this.currency = currency;
        }
    
        public String getCurrencyCN() {
            return currencyCN;
        }
    
        public void setCurrencyCN(String currencyCN) {
            this.currencyCN = currencyCN;
        }
    
        public String getUnit() {
            return unit;
        }
    
        public void setUnit(String unit) {
            this.unit = unit;
        }
    
        public double getRate() {
            return rate;
        }
    
        public void setRate(double rate) {
            this.rate = rate;
        }
    }
    

    我写了一个处理表格的ExcelUtil类,分别对.xls和.xlsx文件进行处理,返回JavaBean的集合对象

    import java.io.FileInputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import com.alibaba.fastjson.JSONObject;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import com.alibaba.fastjson.JSON;
    public class ExcelUtil {
    
        //导入Excel数据
        public List<ConversionRateToDollar> importExcelActionForXLSX(String filePath) throws Exception {
    
            //打开工作簿
            XSSFWorkbook wookbook = new XSSFWorkbook(new FileInputStream(filePath));
    
            //获得第一张表
            XSSFSheet sheet = wookbook.getSheetAt(0);
    
            //获得表内容的第三行第二列单元格,作为日期
            XSSFRow dateRow=sheet.getRow(2);
            XSSFCell dateCell=dateRow.getCell(1);
            String date=dateCell.getStringCellValue();
    
            //获取到Excel文件中的所有行数
            int numberOfRows = sheet.getPhysicalNumberOfRows();
    
            //遍历行(表的第7行开始,是我们想要的数据,最后三行是表的“注”,无需遍历)
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 6; i < numberOfRows - 3; i++) {
    
                // 对单独每行的操作:
                XSSFRow row = sheet.getRow(i);
    
                // 行不为空
                if (row != null) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    //ConversionRateToDollar对象的“month”属性设置为标题的日期
                    String month = date;
    
                    //ConversionRateToDollar对象的“currency”属性
                    XSSFCell currencyCell = row.getCell(1);
                    String currency = getValue(currencyCell);
    
                    //ConversionRateToDollar对象的“currencyCN”属性
                    XSSFCell currencyCNCell = row.getCell(2);
                    String currencyCN = getValue(currencyCNCell);
    
                    //ConversionRateToDollar对象的“unit”属性
                    XSSFCell unitCell = row.getCell(3);
                    String unit = getValue(unitCell);
    
                    //ConversionRateToDollar对象的“rate”属性
                    XSSFCell rateCell = row.getCell(4);
                    String rate = getValue(rateCell);
    
                    map.put("month",month);
                    map.put("currency",currency);
                    map.put("currencyCN",currencyCN);
                    map.put("unit",unit);
                    map.put("rate",rate);
    
                    list.add(map);
                }
            }
            //由于“各种货币对美元折算率”表一行有两个对象,将右边一组的对象按同样方法遍历
            for (int i = 6; i < numberOfRows - 3; i++) {//最后三行是表的注解,不是我们需要的内容
                //对每行的操作
                XSSFRow row = sheet.getRow(i);
                // 行不为空
                if (row != null) {
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    //获取到Excel文件中的所有的列
                    int cells = row.getPhysicalNumberOfCells();
                    String month = "2019-05";
                    XSSFCell currencyCell = row.getCell(5);
                    String currency = getValue(currencyCell);
                    XSSFCell currencyCNCell = row.getCell(6);
                    String currencyCN = getValue(currencyCNCell);
                    XSSFCell unitCell = row.getCell(7);
                    String unit = getValue(unitCell);
                    XSSFCell rateCell = row.getCell(8);
                    String rate = getValue(rateCell);
                    map1.put("month",month);
                    map1.put("currency",currency);
                    map1.put("currencyCN",currencyCN);
                    map1.put("unit",unit);
                    map1.put("rate",rate);
                    list.add(map1);
                }
            }
            //输出list的json
            System.out.println("list = "+JSON.toJSONString(list));
            //将json转化为javaBean
            List<ConversionRateToDollar> conversionRateToDollarList= JSONObject.parseArray(JSON.toJSONString(list),ConversionRateToDollar.class);
            return conversionRateToDollarList;
            //System.out.println("各种货币对美元折算率 对象个数: "+conversionRateToDollarList.size());
        }
        private String getValue(XSSFCell xSSFCell){
            if(null == xSSFCell){
                return "";
            }
            if (xSSFCell.getCellType() == xSSFCell.CELL_TYPE_BOOLEAN) {
                // 返回布尔类型的值  
                return String.valueOf(xSSFCell.getBooleanCellValue());
            } else if (xSSFCell.getCellType() == xSSFCell.CELL_TYPE_NUMERIC) {
                // 返回数值类型的值  
                return String.valueOf(xSSFCell.getNumericCellValue());
            } else {
                // 返回字符串类型的值  
                return String.valueOf(xSSFCell.getStringCellValue());
            }
        }
    
        //导入Excel数据
        public List<ConversionRateToDollar> importExcelActionForXLS(String filePath) throws Exception {
    
    
            //打开工作簿
            HSSFWorkbook wookbook = new HSSFWorkbook(new FileInputStream(filePath));
    
            //获得第一张表
            HSSFSheet sheet = wookbook.getSheetAt(0);
    
            //获得表内容的第三行第二列单元格,作为日期
            HSSFRow dateRow=sheet.getRow(2);
            HSSFCell dateCell=dateRow.getCell(1);
            String date=dateCell.getStringCellValue();
    
            //获取到Excel文件中的所有行数
            int numberOfRows = sheet.getPhysicalNumberOfRows();
    
            //遍历行(表的第7行开始,是我们想要的数据,最后三行是表的“注”,无需遍历)
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 6; i < numberOfRows - 3; i++) {
    
                // 对单独每行的操作:
                HSSFRow row = sheet.getRow(i);
    
                // 行不为空
                if (row != null) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    //ConversionRateToDollar对象的“month”属性设置为标题的日期
                    String month = date;
    
                    //ConversionRateToDollar对象的“currency”属性
                    HSSFCell currencyCell = row.getCell(1);
                    String currency = getValueForXLS(currencyCell);
    
                    //ConversionRateToDollar对象的“currencyCN”属性
                    HSSFCell currencyCNCell = row.getCell(2);
                    String currencyCN = getValueForXLS(currencyCNCell);
    
                    //ConversionRateToDollar对象的“unit”属性
                    HSSFCell unitCell = row.getCell(3);
                    String unit = getValueForXLS(unitCell);
    
                    //ConversionRateToDollar对象的“rate”属性
                    HSSFCell rateCell = row.getCell(4);
                    String rate = getValueForXLS(rateCell);
    
                    map.put("month",month);
                    map.put("currency",currency);
                    map.put("currencyCN",currencyCN);
                    map.put("unit",unit);
                    map.put("rate",rate);
    
                    list.add(map);
                }
            }
            //由于“各种货币对美元折算率”表一行有两个对象,将右边一组的对象按同样方法遍历
            for (int i = 6; i < numberOfRows - 3; i++) {//最后三行是表的注解,不是我们需要的内容
                //对每行的操作
                HSSFRow row = sheet.getRow(i);
                // 行不为空
                if (row != null) {
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    //获取到Excel文件中的所有的列
                    int cells = row.getPhysicalNumberOfCells();
                    String month = "2019-05";
                    HSSFCell currencyCell = row.getCell(5);
                    String currency = getValueForXLS(currencyCell);
                    HSSFCell currencyCNCell = row.getCell(6);
                    String currencyCN = getValueForXLS(currencyCNCell);
                    HSSFCell unitCell = row.getCell(7);
                    String unit = getValueForXLS(unitCell);
                    HSSFCell rateCell = row.getCell(8);
                    String rate = getValueForXLS(rateCell);
                    map1.put("month",month);
                    map1.put("currency",currency);
                    map1.put("currencyCN",currencyCN);
                    map1.put("unit",unit);
                    map1.put("rate",rate);
                    list.add(map1);
                }
            }
            //输出list的json
            System.out.println("list = "+JSON.toJSONString(list));
            //将json转化为javaBean
            List<ConversionRateToDollar> conversionRateToDollarList= JSONObject.parseArray(JSON.toJSONString(list),ConversionRateToDollar.class);
            return conversionRateToDollarList;
        }
        private String getValueForXLS(HSSFCell hSSFCell){
            if(null == hSSFCell){
                return "";
            }
            if (hSSFCell.getCellType() == hSSFCell.CELL_TYPE_BOOLEAN) {
                // 返回布尔类型的值  
                return String.valueOf(hSSFCell.getBooleanCellValue());
            } else if (hSSFCell.getCellType() == hSSFCell.CELL_TYPE_NUMERIC) {
                // 返回数值类型的值  
                return String.valueOf(hSSFCell.getNumericCellValue());
            } else {
                // 返回字符串类型的值  
                return String.valueOf(hSSFCell.getStringCellValue());
            }
        }
    }
    

    实现定时任务

    在SpringBoot的启动类添加注解

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    @SpringBootApplication
    @EnableScheduling
    public class GetExcelByHref {
        public static void main(String[] args) {
            SpringApplication.run(GetExcelByHref.class,args);
        }
    }
    

    配置组件,在里面写入需要定时执行的任务方法,使用cron表达式。本来表达式应该配置为每月初执行,这里为了测试效果写了一个每五分钟执行一次。

    @Component
    public class GetConversionRateToDollar {
        @Scheduled(cron = "0 0/5 * * * *")
        public void getConversionRateToDollar() throws IOException {
        .....
            }
    }
    

    源代码

    package com.crawler;
    
    public class ConversionRateToDollar {
        private String month;
        private String currency;
        private String currencyCN;
        private String unit;
        private double rate;
    
        public String getMonth() {
            return month;
        }
    
        public void setMonth(String month) {
            this.month = month;
        }
    
        public String getCurrency() {
            return currency;
        }
    
        public void setCurrency(String currency) {
            this.currency = currency;
        }
    
        public String getCurrencyCN() {
            return currencyCN;
        }
    
        public void setCurrencyCN(String currencyCN) {
            this.currencyCN = currencyCN;
        }
    
        public String getUnit() {
            return unit;
        }
    
        public void setUnit(String unit) {
            this.unit = unit;
        }
    
        public double getRate() {
            return rate;
        }
    
        public void setRate(double rate) {
            this.rate = rate;
        }
    }
    
    
    package com.crawler;
    import java.io.FileInputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import com.alibaba.fastjson.JSONObject;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import com.alibaba.fastjson.JSON;
    public class ExcelUtil {
    
        //导入Excel数据
        public List<ConversionRateToDollar> importExcelActionForXLSX(String filePath) throws Exception {
    
            //打开工作簿
            XSSFWorkbook wookbook = new XSSFWorkbook(new FileInputStream(filePath));
    
            //获得第一张表
            XSSFSheet sheet = wookbook.getSheetAt(0);
    
            //获得表内容的第三行第二列单元格,作为日期
            XSSFRow dateRow=sheet.getRow(2);
            XSSFCell dateCell=dateRow.getCell(1);
            String date=dateCell.getStringCellValue();
    
            //获取到Excel文件中的所有行数
            int numberOfRows = sheet.getPhysicalNumberOfRows();
    
            //遍历行(表的第7行开始,是我们想要的数据,最后三行是表的“注”,无需遍历)
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 6; i < numberOfRows - 3; i++) {
    
                // 对单独每行的操作:
                XSSFRow row = sheet.getRow(i);
    
                // 行不为空
                if (row != null) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    //ConversionRateToDollar对象的“month”属性设置为标题的日期
                    String month = date;
    
                    //ConversionRateToDollar对象的“currency”属性
                    XSSFCell currencyCell = row.getCell(1);
                    String currency = getValue(currencyCell);
    
                    //ConversionRateToDollar对象的“currencyCN”属性
                    XSSFCell currencyCNCell = row.getCell(2);
                    String currencyCN = getValue(currencyCNCell);
    
                    //ConversionRateToDollar对象的“unit”属性
                    XSSFCell unitCell = row.getCell(3);
                    String unit = getValue(unitCell);
    
                    //ConversionRateToDollar对象的“rate”属性
                    XSSFCell rateCell = row.getCell(4);
                    String rate = getValue(rateCell);
    
                    map.put("month",month);
                    map.put("currency",currency);
                    map.put("currencyCN",currencyCN);
                    map.put("unit",unit);
                    map.put("rate",rate);
    
                    list.add(map);
                }
            }
            //由于“各种货币对美元折算率”表一行有两个对象,将右边一组的对象按同样方法遍历
            for (int i = 6; i < numberOfRows - 3; i++) {//最后三行是表的注解,不是我们需要的内容
                //对每行的操作
                XSSFRow row = sheet.getRow(i);
                // 行不为空
                if (row != null) {
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    //获取到Excel文件中的所有的列
                    int cells = row.getPhysicalNumberOfCells();
                    String month = "2019-05";
                    XSSFCell currencyCell = row.getCell(5);
                    String currency = getValue(currencyCell);
                    XSSFCell currencyCNCell = row.getCell(6);
                    String currencyCN = getValue(currencyCNCell);
                    XSSFCell unitCell = row.getCell(7);
                    String unit = getValue(unitCell);
                    XSSFCell rateCell = row.getCell(8);
                    String rate = getValue(rateCell);
                    map1.put("month",month);
                    map1.put("currency",currency);
                    map1.put("currencyCN",currencyCN);
                    map1.put("unit",unit);
                    map1.put("rate",rate);
                    list.add(map1);
                }
            }
            //输出list的json
            System.out.println("list = "+JSON.toJSONString(list));
            //将json转化为javaBean
            List<ConversionRateToDollar> conversionRateToDollarList= JSONObject.parseArray(JSON.toJSONString(list),ConversionRateToDollar.class);
            return conversionRateToDollarList;
            //System.out.println("各种货币对美元折算率 对象个数: "+conversionRateToDollarList.size());
        }
        private String getValue(XSSFCell xSSFCell){
            if(null == xSSFCell){
                return "";
            }
            if (xSSFCell.getCellType() == xSSFCell.CELL_TYPE_BOOLEAN) {
                // 返回布尔类型的值  
                return String.valueOf(xSSFCell.getBooleanCellValue());
            } else if (xSSFCell.getCellType() == xSSFCell.CELL_TYPE_NUMERIC) {
                // 返回数值类型的值  
                return String.valueOf(xSSFCell.getNumericCellValue());
            } else {
                // 返回字符串类型的值  
                return String.valueOf(xSSFCell.getStringCellValue());
            }
        }
    
        //导入Excel数据
        public List<ConversionRateToDollar> importExcelActionForXLS(String filePath) throws Exception {
    
    
            //打开工作簿
            HSSFWorkbook wookbook = new HSSFWorkbook(new FileInputStream(filePath));
    
            //获得第一张表
            HSSFSheet sheet = wookbook.getSheetAt(0);
    
            //获得表内容的第三行第二列单元格,作为日期
            HSSFRow dateRow=sheet.getRow(2);
            HSSFCell dateCell=dateRow.getCell(1);
            String date=dateCell.getStringCellValue();
    
            //获取到Excel文件中的所有行数
            int numberOfRows = sheet.getPhysicalNumberOfRows();
    
            //遍历行(表的第7行开始,是我们想要的数据,最后三行是表的“注”,无需遍历)
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            for (int i = 6; i < numberOfRows - 3; i++) {
    
                // 对单独每行的操作:
                HSSFRow row = sheet.getRow(i);
    
                // 行不为空
                if (row != null) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    //ConversionRateToDollar对象的“month”属性设置为标题的日期
                    String month = date;
    
                    //ConversionRateToDollar对象的“currency”属性
                    HSSFCell currencyCell = row.getCell(1);
                    String currency = getValueForXLS(currencyCell);
    
                    //ConversionRateToDollar对象的“currencyCN”属性
                    HSSFCell currencyCNCell = row.getCell(2);
                    String currencyCN = getValueForXLS(currencyCNCell);
    
                    //ConversionRateToDollar对象的“unit”属性
                    HSSFCell unitCell = row.getCell(3);
                    String unit = getValueForXLS(unitCell);
    
                    //ConversionRateToDollar对象的“rate”属性
                    HSSFCell rateCell = row.getCell(4);
                    String rate = getValueForXLS(rateCell);
    
                    map.put("month",month);
                    map.put("currency",currency);
                    map.put("currencyCN",currencyCN);
                    map.put("unit",unit);
                    map.put("rate",rate);
    
                    list.add(map);
                }
            }
            //由于“各种货币对美元折算率”表一行有两个对象,将右边一组的对象按同样方法遍历
            for (int i = 6; i < numberOfRows - 3; i++) {//最后三行是表的注解,不是我们需要的内容
                //对每行的操作
                HSSFRow row = sheet.getRow(i);
                // 行不为空
                if (row != null) {
                    Map<String, Object> map1 = new HashMap<String, Object>();
                    //获取到Excel文件中的所有的列
                    int cells = row.getPhysicalNumberOfCells();
                    String month = "2019-05";
                    HSSFCell currencyCell = row.getCell(5);
                    String currency = getValueForXLS(currencyCell);
                    HSSFCell currencyCNCell = row.getCell(6);
                    String currencyCN = getValueForXLS(currencyCNCell);
                    HSSFCell unitCell = row.getCell(7);
                    String unit = getValueForXLS(unitCell);
                    HSSFCell rateCell = row.getCell(8);
                    String rate = getValueForXLS(rateCell);
                    map1.put("month",month);
                    map1.put("currency",currency);
                    map1.put("currencyCN",currencyCN);
                    map1.put("unit",unit);
                    map1.put("rate",rate);
                    list.add(map1);
                }
            }
            //输出list的json
            System.out.println("list = "+JSON.toJSONString(list));
            //将json转化为javaBean
            List<ConversionRateToDollar> conversionRateToDollarList= JSONObject.parseArray(JSON.toJSONString(list),ConversionRateToDollar.class);
            return conversionRateToDollarList;
        }
        private String getValueForXLS(HSSFCell hSSFCell){
            if(null == hSSFCell){
                return "";
            }
            if (hSSFCell.getCellType() == hSSFCell.CELL_TYPE_BOOLEAN) {
                // 返回布尔类型的值  
                return String.valueOf(hSSFCell.getBooleanCellValue());
            } else if (hSSFCell.getCellType() == hSSFCell.CELL_TYPE_NUMERIC) {
                // 返回数值类型的值  
                return String.valueOf(hSSFCell.getNumericCellValue());
            } else {
                // 返回字符串类型的值  
                return String.valueOf(hSSFCell.getStringCellValue());
            }
        }
    }
    
    package com.crawler;
    
    import org.apache.commons.io.FileUtils;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    import org.jsoup.select.Elements;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.List;
    
    @Component
    public class GetConversionRateToDollar {
        @Scheduled(cron = "0 0/5 * * * *")
        public void getConversionRateToDollar() throws IOException {
            /**
             1.创建HttpClient对象;
             2.创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象;
             3.如果需要发送请求参数,可调用HttpGet,HttpPost共同的setParams(HttpParams params)方法来添加请求参数;
             4.调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse;
             5.调用HttpResponse的getAllHeaders().getHeaders(String name)等方法可获得服务器的响应头;调用HttpResponse的get
             6.释放连接,无论执行方法是否成功,都必须释放资源
             */
            //创建HttpClientBuilder
            HttpClientBuilder httpClientBuilder= HttpClientBuilder.create();
            //创建HttpClient
            CloseableHttpClient closeableHttpClient=httpClientBuilder.build();
            HttpGet httpGet=new HttpGet("http://www.safe.gov.cn/safe/gzhbdmyzslb/index.html");
            System.out.println(httpGet.getRequestLine());
            try {
                String urlHeader = "http://www.safe.gov.cn";
                //执行get请求
                HttpResponse httpResponse = closeableHttpClient.execute(httpGet);
                //获取响应消息实体
                HttpEntity entity = httpResponse.getEntity();
                //响应状态
                System.out.println("status:" + httpResponse.getStatusLine());
                if (entity != null) {
                    System.out.println("contentEncoding:" + entity.getContentEncoding());
                    //返回html文本信息
                    String response = EntityUtils.toString(entity, "UTF-8");
                    //System.out.println(response);
    
                    //解析页面内容
                    Document document= Jsoup.parse(response);
    
                    //根据唯一标识获得className为"list_conr"的标签
                    Elements listConr = document.getElementsByClass("list_conr");
    
                    //主页按照不同月份有不同链接,是一个列表,我们需要获得最新的月份,即第一个列表里的链接,该链接能打开表格下载的网页
                    Element ahref=listConr.select("ul").get(0).select("li").get(0).selectFirst("dt").selectFirst("a");
                    String hrefDetail=ahref.attr("href");
    
                    //新的页面,创建新的HttpClientBuilder
                    HttpClientBuilder httpClientBuilder1= HttpClientBuilder.create();
    
                    //创建HttpClient
                    CloseableHttpClient closeableHttpClient1=httpClientBuilder1.build();
    
                    //请求某个月份的表格下载页面
                    HttpGet httpGet1=new HttpGet(urlHeader+hrefDetail);
                    System.out.println(httpGet.getRequestLine());
    
                    try {
                        //执行get请求
                        HttpResponse httpResponse1 = closeableHttpClient1.execute(httpGet1);
    
                        //获取响应消息实体
                        HttpEntity entity1 = httpResponse1.getEntity();
    
                        //响应状态
                        System.out.println("status:" + httpResponse1.getStatusLine());
    
                        if(entity1!=null){
                            //html文本信息
                            String response1 = EntityUtils.toString(entity1, "UTF-8");
                            //System.out.println(response1);
    
                            //解析页面内容
                            Document document1= Jsoup.parse(response1);
    
                            //获得xlsx的下载链接url
                            Element axlsxhref=document1.getElementsByClass("detail_content").first().select("div").first().select("p").get(2).select("a").first();
                            String axlsxhrefDetail=axlsxhref.attr("href");
                            String url = urlHeader+axlsxhrefDetail;
    
                            //创建httpClient实例
                            CloseableHttpClient httpClient3 = HttpClients.createDefault();
                            //创建httpGet实例
                            HttpGet httpGet3 = new HttpGet(url);
    
                            //获得页面响应
                            CloseableHttpResponse response3 = httpClient3.execute(httpGet3);
    
                            //获取.后缀,为"xlsx"
                            String fileType = url.substring(url.lastIndexOf("."), url.length());
    
                            if (response3 != null){
                                HttpEntity entity3 = response3.getEntity();
                                if (entity3 != null){
    
    //                                //如果设置定时任务,那么在文件标题中显示上个月的月份,便于区分
    //                                Calendar calendar=Calendar.getInstance();
    //                                calendar.add(Calendar.MONTH,-1);
    //                                String date=new SimpleDateFormat("yyyy年MM月").format(calendar.getTime());
    
                                    SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日HH_mm_ss");
                                    String date=dateFormat.format(new Date());
    
                                    //文件复制
                                    InputStream inputStream = entity3.getContent();
                                    FileUtils.copyToFile(inputStream,new File("E:\\rmbrate\\rate"+date+fileType));
    
                                    List<ConversionRateToDollar> conversionRateToDollarList=new ArrayList<ConversionRateToDollar>();
                                    ExcelUtil excelUtil=new ExcelUtil();
                                    try {
                                        //.xlsx后缀
                                        if (fileType.equals(".xlsx")) {
                                            conversionRateToDollarList=excelUtil.importExcelActionForXLSX("E:\\rmbrate\\rate"+date+fileType);
                                        }
                                        //.xls后缀
                                        else if (fileType.equals(".xls")) {
                                            conversionRateToDollarList=excelUtil.importExcelActionForXLS("E:\\rmbrate\\rate"+date+fileType);
                                        }
                                        System.out.println(conversionRateToDollarList.size());
    
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                            if (response3 != null){
                                response3.close();
                            }
                            if (httpClient3 != null){
                                httpClient3.close();
                            }
                        }
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                    finally {
                        try {
                            closeableHttpClient1.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
    
                }
            }catch (IOException e){
                e.printStackTrace();
            }
            finally {
                try {
                    closeableHttpClient.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
    
    
    package com.crawler;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    @SpringBootApplication
    @EnableScheduling
    public class GetExcelByHref {
        public static void main(String[] args) {
            SpringApplication.run(GetExcelByHref.class,args);
        }
    }
    
    

    运行结果

    每五分钟成功执行
    每五分钟执行 获得了表
    获得json
    输出了json

    展开全文
  • Springboot2 定时任务

    千次阅读 2018-07-07 15:26:34
    java List<String> 转换成带逗号的字符串 使用commons-lang3-3.3.2.jar ...org.apache.commons.lang3.StringUtils.join...1、启动类加注解,开启定时任务 @EnableScheduling 2、添加定时任务类...

     

     

    java List<String> 转换成带逗号的字符串

     

    使用commons-lang3-3.3.2.jar

     

     

    org.apache.commons.lang3.StringUtils.join(applyNameList, ",");

     

     

     

    1、启动类加注解,开启定时任务

    @EnableScheduling

     

    2、添加定时任务类

    package com.ukefu.mybatis.ps.sms.quartz;
    
    import com.ukefu.mybatis.ps.sms.entity.SendRecord;
    import com.ukefu.mybatis.ps.sms.service.SendRecordService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.List;
    
    /**
     * Created by Admin on 2018/6/7.
     */
    @Component
    public class QuartzSendMessage {
        @Autowired
        SendRecordService sendRecordService;
    
        //    每分钟启动
        @Scheduled(cron = "0/10 * * * * ?")
        public void timerToNow(){
            List<SendRecord> sendRecords = sendRecordService.findCronSendRecord();
            if (sendRecords != null && sendRecords.size()>0){
                sendRecordService.cronsend(sendRecords);
            }
    
        }
    }
    

     

    展开全文
  • Spring boot 定时任务

    2019-05-08 19:46:15
    demo测试通过,使用版本...新建一个java类,添加注解@Configuration和@EnableScheduling,开启调度任务。在类中新建一个定时的方法添加注解@Scheduled ,表明该方法是一个调度任务。cron表达式配置定时执行的规则...
  • ubuntu 定时任务基础

    2018-07-05 15:19:23
    首先系统得安装PHP 和apache 编写测试php文件cron.php 用php执行cron.php   生成文件OK 下面是crontab 的内容 crontab -e 编辑周期...设定每五分钟执行一次 默认开启cron服务  完成       ...
  • 下面开始使用@Schedule来开启定时任务,github:https://github.com/fengqing11/springboot–Schedule 创建项目,依赖如下: <?xml version="1.0" encoding="UTF-8"?> <project xmlns=...
  • 最近在思考队列怎么一直开启,一直执行的问题,想到了可以写一个死循环,不停的去执行 用nohup挂在就可以了   因为mac自带PHP和apahce 只需要用root用户启动apache sudo apachectl restart PHP启动方式为 ...
  • CDH6.3.3 开启kerberos 认证 kafka-eagle:2.0 system-config.properties 关键配置: cluster1.kafka.eagle.offset.storage=kafka cluster1.kafka.eagle.sasl.enable=true cluster1.kafka.eagle.sasl.protocol...
  • 问题描述:在一台以上配置的电脑,开启一两个小时后cpu占用从0%变成18%,没有定时任务,有6个线程都占用3.11%的cpu(在其他电脑上系统版本和jdk tomcat mysql版本一样未出现该种情况) 通过jstack吧进程...
  • ssm使用shiro启动报错

    2018-03-11 11:35:00
    -- 开启定时任务 --> <!-- MyBatis配置 --> <!-- 显式指定Mapper文件位置 --> *:/mybatis/*Mapper.xml" /> <!-- mybatis配置文件路径 --> <!-- 这个执行器会批量执行更新语句, 还有...
  • 1.29 ftpshut指令:定时关闭ftp服务器 1.30 ftpwho指令:显示登录ftp用户信息 1.31 gunzip指令:解压缩文件 1.32 gzexe指令:压缩可执行文件 1.33 gzip指令:压缩文件 1.34 indent指令:调整C原始代码文件的格式 ...
  • 前台:nignx 后台:...定时任务: 【开启RZ命令】 yum -y install lrzsz 【防火墙】 防火墙配置文件: /etc/sysconfig/iptables 服务操作命令 : /etc/init.d/iptables service iptables {start|stop...} 临时
  • linux关闭服务

    千次阅读 2019-04-01 15:38:52
    crond 系统的定时任务,一般的 Linux 服务器都需要定时任务来协助系统维护。建议开启 开启 httpd apache 服务的守护进程。如果需要启动 apache,就开启 开启 mysqld MySQL 数据库服务器。如果需要就开启;否则关闭 ....
  • 1.判断apache服务是否正常,如果不正常则重启,并且输出信息到屏幕,把服务信息写入到一个新的文件中,可以把这个脚本加入到循环定时任务里面去 # 判断apache服务是否开启,如果没有开启则将其自动开启 test=$(ps ...
  • nginx yum安装

    千次阅读 2016-09-08 10:44:21
    定时任务: 【开启RZ命令】 yum -y install lrzsz 【防火墙】 防火墙配置文件: /etc/sysconfig/iptables 服务操作命令 : /etc/init.d/iptables service iptables {start|stop...} 临时
  • CentOs6.4安装lnmp

    2016-11-01 18:12:31
    定时任务: 【开启RZ命令】 yum -y install lrzsz 【防火墙】 防火墙配置文件: /etc/sysconfig/iptables 服务操作命令 : /etc/init.d/iptables service iptables {start|stop...} 临时
  • linux上的nginx安装

    2016-10-23 19:13:16
    定时任务: 【开启RZ命令】 yum -y install lrzsz 【防火墙】 防火墙配置文件: /etc/sysconfig/iptables 服务操作命令 : /etc/init.d/iptables service iptables {start|stop...} 临时
  • 安装nginx apach

    2016-09-06 08:12:57
    定时任务: 【开启RZ命令】 yum -y install lrzsz 【防火墙】 防火墙配置文件: /etc/sysconfig/iptables 服务操作命令 : /etc/init.d/iptables service iptables {start|stop...} 临时
  • Linux博文目录

    2012-01-03 11:21:00
    2014-10 ... 2014-03 tomcat服务器不输出访问日志 2013-07 Ubuntu下启动Apache的Rewrite功能 ...Apache 实现Web Server 负载均衡,不考虑Session版 ...ubuntu下定时执行工具cron开启关闭重启 2012-8...
  • 前台:nignx 后台:apache【linux命令】用户文件目录启动定时任务:【开启RZ命令】yum -y install lrzsz 【防火墙】防火墙配置文件: /etc/sysconfig/iptables服务操作命令 : /etc/init.d/iptables service ...
  • 序 当设置了remove-abandoned=true后,就开启了连接池连接泄露的检查。...定时任务 org.apache.tomcat.jdbc.pool#PoolCleaner protected static class PoolCleaner extends TimerTask { protected WeakRef...
  • php 定时器

    2020-06-01 21:59:47
    // 启动apache app 目录下添加 cron-run 访问首页 启动 定时任务第一次执行的时间是每晚的11.55 //如果不存在cron-switch这个文件,就停止执行,这是一个开关的作用 function dowhile() { //11.55维护 5分钟 禁止...

空空如也

1 2
收藏数 28
精华内容 11
关键字:

定时任务开启apache