编写一个程序,读取conf.txt的第一行,自动按照每5秒执行一次A.f1():

发布于:2022-12-18 ⋅ 阅读:(420) ⋅ 点赞:(0)

编写一个程序,读取conf.txt的第一行,自动按照每5秒执行一次A.f1():

给定一个A.java,可以带包名。


‌//===========


‌class A


‌{


‌ public void f1()


‌ {


‌ System.out.println(“hello java”);


‌ }


‌}


‌//===========



‌再给定一个conf.txt,里面的内容如下


‌#==============


‌A,f1,5


‌#==============



‌请编写一个程序,读取conf.txt的第一行,自动按照每5秒执行一次A.f1():

效果如下:

在这里插入图片描述
代码:

import java.io.*;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author: zky
* @date: 2022/09/14
*/
public class Main {
   public static void main(String[] args) throws Exception {
	   // 修改为自己的文件路径
       RandomAccessFile randomAccessFile = new RandomAccessFile("src/conf.txt", "r");

       if(Objects.isNull(randomAccessFile)) {
           System.err.println("目标文件不存在");
       }

       String s = randomAccessFile.readLine();
       String[] strings = s.split(",");

       // 反射获取类
       Class<?> aClass = Main.class.getClassLoader().loadClass(strings[0]);
       Object o = aClass.newInstance();

       // 获取方法
       Method method = aClass.getMethod(strings[1]);

       // 定时调用
       Timer timer = new Timer();
       timer.scheduleAtFixedRate(new TimerTask() {
           @Override
           public void run() {
               System.out.println("现在的时间为:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
               try {
                   method.invoke(o, null);
               } catch (Exception e) {
                   System.err.println("方法调用失败!");
               }
           }
       },0,  Integer.valueOf(strings[2]) * 1000);

   }

}

网站公告

今日签到

点亮在社区的每一天
去签到