import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.lang.management.ManagementFactory; import com.sun.management.OperatingSystemMXBean; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask;

public class MemoryTimerTask { public static void main(String[] args) { TimerTask task = new TimerTask() { @Override public void run() { // 获取当前时间 Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss'); String currentTime = sdf.format(date);

            // 获取内存使用情况
            OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
            long totalMemorySize = osmxb.getTotalPhysicalMemorySize();
            long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();
            long usedPhysicalMemorySize = totalMemorySize - freePhysicalMemorySize;
            
            // 将内存使用情况写入文件
            BufferedWriter writer = null;
            try {
                writer = new BufferedWriter(new FileWriter('memory.txt', true));
                writer.write('时间:' + currentTime + '; ');
                writer.write('总的物理内存:' + totalMemorySize + '; ');
                writer.write('剩余物理内存:' + freePhysicalMemorySize + '; ');
                writer.write('已使用物理内存:' + usedPhysicalMemorySize + '\n');
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };
    
    Timer timer = new Timer();
    // 获取当前时间
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat('ss');
    int seconds = Integer.parseInt(sdf.format(date));
    // 计算下一个整分时刻
    long delay = (60 - seconds) * 1000;
    // 每隔一分钟执行一次
    timer.scheduleAtFixedRate(task, delay, 60 * 1000);
}

}

Java 定时任务:每分钟记录内存使用情况

原文地址: https://www.cveoy.top/t/topic/ngEE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录