在java

时间:2018-03-13 06:05:23

标签: java multithreading scheduler

我有一个预定的java方法,它在特定时间每天执行两次,进行一些处理,通常需要大约一个小时才能完成。

现在,在这个小时内,我需要在文本文件中输出一些方法信息,比如说每15分钟一次(基本上作为元信息,在处理过程中会改变一些变量值),所以这将打印4次特别的方法。

我已经编写了一个单独的打印方法,但我不确定如何将其与我上面的计划方法集成。这是代码:

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class MainClass {

    private static Timer timer = new Timer();

    public static void print(){
         timer.schedule (new MyTask(),0,1000*60*15);
    }
}

class MyTask extends TimerTask {
      public void run() {
          PrintWriter writer =  null;
          String configurationFilePath ="job-configurations.txt";
          try{
              File file = new File(configurationFilePath);
              if(!file.exists()){
                  file.createNewFile();
              }
              writer = new PrintWriter(file, "UTF-8");
              writer.println("User Agent: "+ useragent);

              writer.println("Location: "+country);
          } catch (IOException e) {
              LOGGER.error("Unable to add UA/Loc log file " + e.getMessage());
          } finally {
               if(writer != null){
                  writer.close();
               }
          }
      }

}

如何在调度方法完成执行时调用主类的print方法并使其停止。

1 个答案:

答案 0 :(得分:1)

你可以在Main class 1中制作2个静态方法来开始打印另一个以停止打印,并可以从另一个类中调用它们。

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Timer;
import java.util.TimerTask;

public class MainClass {

    private static Timer timer = new Timer();

    public static void startPrint(){
         timer.schedule (new MyTask(),0,1000*60*15);
    }

    public static void stopPrint() {
        timer.cancel();
    }
}

class MyTask extends TimerTask {
      public void run() {
          PrintWriter writer =  null;
          String configurationFilePath ="job-configurations.txt";
          try{
              //start timer
              MainClass.startPrint();
              File file = new File(configurationFilePath);
              if(!file.exists()){
                  file.createNewFile();
              }
              writer = new PrintWriter(file, "UTF-8");

              writer.println("User Agent: "+ useragent);

              writer.println("Location: "+country);
          } catch (IOException e) {
              LOGGER.error("Unable to add UA/Loc log file " + e.getMessage());
          } finally {
               if(writer != null){
                  writer.close();
               }

               //Stop Timer
               MainClass.stopPrint();
          }
      }

}