简体   繁体   中英

Start jar file with TimerTask schedule in background in linux

I am trying to run my application from a jar file in background. I've already tried nohup and & but they don't work.

nohup java -cp ~/DataGenerator/target/GenerateDataApp-1.0-SNAPSHOT.jar Generator.App -p ~/Text2.txt &

My application is a simple timer that runs every 1s, generating a random number every time and saving it to a file.

public class App {
    public static void main(String[] args) throws Exception{
        System.out.println("Start");
        Arguments arguments = Arguments.fromMain(args);
        SaveToFile saveToFile = new SaveToFile();
        saveToFile.creatFile(arguments.getPathToPropertiesFile());
        Timer timer = new Timer();
        timer.schedule(new SaveFileRunner(arguments), 0, 100);
        

    }
}

I also tried the bash script, but it didn't help either.

#!/bin/sh
cd ~/DataGenerator/target
java -cp ~/DataGenerator/target/GenerateDataApp-1.0-SNAPSHOT.jar Generator.App -p ~/Text.txt

Could someone advise me how can I make a timer work in the backend?

To make a program run as a background job, add & to the end of the command line. For example:

java ...parameters here... &

A possible problem with this is if the program writes output, that is still displayed in the terminal. You can send that output to a file.

java ...parameters here... >output.txt 2>&1 &

A second problem is that if you close the shell or logout, the program is stopped. To avoid that, use nohup.

nohup java ...parameters here... >output.txt 2>&1 &

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM