Java – Put CPU % into a local file by Cron job No.81

How to save the current CPU % on Ubuntu into a local file by Cron job with an execution of Jar is shown in this blog.

▼1. How to export the current CPU % on Ubuntu

The command “top -b -n 1” is executed by Java and save only CPU % into a file.


▼2. Prerequisites

This blog is based on Java – Capture CPU,Memory,Network info on Ubuntu No.79.


▼3. Java code to export the current CPU % on Ubuntu

3-1. Develop perfch2.java

“perfch2.java” run the command “top -b -n 1” and save only CPU % into a file by Java. the file name of output is CPU{epochmilliseconds}.txt when file is created.

// the file contains below

INFO: %Cpu(s): 11.1 us
package org.example.perflog;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.Instant;
import java.util.logging.Level;
import java.util.logging.Logger;

public class perfch2 {

    private static final Logger log;

    static{
        log = Logger.getLogger(perfch2.class.getName());
    }

    public static void main(String[] args) {
        //System.out.println("top -b -n 1");
        try {
            Process p = Runtime.getRuntime().exec("top -b -n 1");
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            int i = 0;
            // set j to current local time
            long j = Instant.now().toEpochMilli();

            while ((line = br.readLine()) != null && i < 3) {
                if(i == 2) {
                    // extract string until comma
                    String[] parts = line.split(",");
                    String part1 = parts[0]; 
                    log.log(Level.INFO, part1);
                    
                    // save part1 to file
                    String filename = "/home/ubuntu20/temp/cpu"+ j +".log";
                    java.io.PrintWriter output = new java.io.PrintWriter(filename);
                    output.println(part1);
                    output.close();
                }
                i++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3-2. Export Jar file

Ref: Lightweight Mode, Maven Support, Java Package, and Dependency Management in Visual Studio Code

3-3. Set execution time in Crontab

e.g) Run jar file at 19:24

crontab -e
xxx

 For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command
24 19 * * * $JAVA_HOME/bin/java -jar /home/ubuntu20/coding/javatest/perfcheck/perfcheck.jar

3-4. Check the saved file after running a cron Job

Epoch milliseconds 1669112641416 means 2022/11/22 19:24:01.

//Cpu1669112641416.txt

%Cpu(s): 11.8 us

▼4. 参考情報

That’s all. Have a nice day ahead !!!

Leave a Reply

Your email address will not be published. Required fields are marked *