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


    编写一个程序,读取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);
    
       }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
  • 相关阅读:
    热熔胶行业调研:2022年热熔胶市场发展现状与前景分析
    Spring AOP 分享
    中文编程工具免费版下载,中文开发语言工具免费版下载
    C# —— 方法的参数列表
    2022 年 10 月区块链操作系统的开发回顾
    【ElasticSearch】DSL查询文档
    JDK 19 协程新特性学习
    js中的i++和++i
    Flutter高仿微信-第55篇-群聊-合成群头像
    PRC是什么 | 图解系列
  • 原文地址:https://blog.csdn.net/qq_53578500/article/details/126849084